I\'m working on a mat-table
which implements pagination, filtering, selection, etc. I have this mat-select
on one of the header columns which I use
This is a little bit of a "workaround", but I wonder if you could leverage:
@Output() openedChange: EventEmitter
Event emitted when the select panel has been toggled.
And fire your function any time the select is changed or closed, as I believe that is essentially what you're looking to accomplish.
However, you might have to add some logic to prevent your function from being fired twice.
I know this is late, but I've come to find a solution.
Normally, we would be using @Output() selectionChange
to pass the selected value to a function in our .ts
file and do what we want there. But this doesn't work if we select the same value.
Solution:
So what we need to do instead is use @Output() openedChange
which will pass true
(opened) or false
(closed). We are interested in when we close the mat-select component. Unfortunately openedChange doesn't have direct access to the value we selected. So we simply make a member variable which is binded to the value we select, and whenever openedChange is triggered and returns false, we will use that member variable.
Here's the basic code:
your-component.component.html
<mat-form-field>
<mat-label>Options</mat-label>
<mat-select *ngFor="let option of allOptions;"
(openedChange)="onSelectionChange($event)"
[(value)]="selectedVariable">
<mat-option [value]="option">
{{option.name}}
</mat-option>
</mat-select>
</mat-form-field>
your-component.component.ts
selectedVariable: any;
constructor() {}
ngOnInit() {
//...
}
onSelectionChange(opened: boolean) {
if (!opened && this.selectedVariable) {
// Do whatever you want here with `this.selectedVariable`
console.log(this.selectedVariable);
}
}
Note: In the onSelectionChange function, you need to make sure that something was actually selected. Because otherwise the function will continue if a user clicks on the select, and clicks away from it without selecting anything.