Reputation: 296
I have a multiple mat-select
and would like to know if the mat-option
that's been clicked has been selected or deselected. The $event.target
object passed when the (click)
is fired has no selected
attribute I could use.
<mat-form-field>
<mat-select [formControl]="control" multiple>
<mat-option
*ngFor="let option of options"
[value]="option"
(click)="foo($event)"
>
{{ option }}
</mat-option>
</mat-select>
</mat-form-field>
public foo(event) {
const hasBeenChecked = ???? // How do I know if my clicked option has been checked or unchecked?
}
Thanks in advance
Upvotes: 12
Views: 35385
Reputation: 2437
Using Angular 11.0 worked to add in the mat-option tag the (click) event see below:
<mat-option (click)="handleSelected(option)" *ngFor="let option of filteredOptions | async" [value]="option">
And you get the displayed value
Upvotes: 5
Reputation: 73367
You are already using a formcontrol. All your selected options are there, stored in an array:
foo(x) {
// an array of your selections
console.log(this.control.value)
}
So you don't need to track if it's unchecked or checked.
Upvotes: -1
Reputation: 6986
You can get the selected state of the clicked option by reading it off of the MatOption object as follows:
<mat-option #matOption (click)="foo(matOption.selected)"></mat-option>
Upvotes: 19
Reputation: 8292
You can use selectionChange()
event on <mat-select>
which will give you the option you selected.
<mat-select (selectionChange)="foo($event)">
The best practice would be to get the change straight from FormControl. If you console.log
the FormControl you use: [formControl]="control"
, you will see that it holds the last selected option. If you have multiple mat-selects, and would like to have them in control, my suggestion is to wrap them in a FormGroup
and then use FormControl
which belongs to that FormGroup
for each of the selects.
Upvotes: 3