Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 443
Jota Renan Avatar asked Aug 14 '19 14:08

Jota Renan


People also ask

How do you check mat option is selected or not?

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.

What is a mat select trigger?

MatSelectTrigger. Allows the user to customize the trigger that is displayed when the select has a value.

How do you set mat option selected value?

Create Select using <mat-select> To add elements to select option, we need to use <mat-option> element. To bind value with <mat-option> , we need to use value property of it. The <mat-select> has also value property to bind selected value to keep it selected. We need to use <mat-select> inside <mat-form-field> element.


Video Answer


1 Answers

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

like image 88
Sam Herrmann Avatar answered Nov 16 '22 15:11

Sam Herrmann