简体   繁体   中英

How to know if a mat-option is selected or not from a click event?

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

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>

StackBlitz Example

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.

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

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.

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM