10

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

Jota Renan
  • 266
  • 2
  • 4
  • 11

4 Answers4

18

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

Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50
5

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

George Vardikos
  • 2,345
  • 1
  • 14
  • 25
2

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.

Dino
  • 7,779
  • 12
  • 46
  • 85
-1

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

AT82
  • 71,416
  • 24
  • 140
  • 167