简体   繁体   中英

Identify the option that was clicked in a mat-select with multi-select

For a multi-select as shown below, I would like to know which option was last selected by the user in the selectionChange event.

The intention is to identify any click to the 'All' option and ignore it while still being able to process other options in selectionChange event. Any other strategy is also welcome.

带有多个选项的 mat-select 屏幕截图

<mat-select
  [multiple]="true"
  formControlName="selectCtrl"
  (selectionChange)="onSelectionChange($event)"
>
    <mat-option
      #allOption
      [value]="allSelectOption"
      (click)="toggleMultiAll(allOption.selected)"
    >
        {{ allSelectOption.displayText }}
    </mat-option>
    <mat-option *ngFor="let option of filteredOptions" [value]="option">
        {{ option.displayText }}
    </mat-option>
</mat-select>
onSelectionChange(event) {
    if (_condition_) {  // If clicked option is 'All', ignore
        return;
    }
    this.selectedOptions$.next(event.value);
}

To check if the option is All we can use array.includes .

The event return an object with two properties: source and value .

value is the one we will use. Because it's an array, we can use includes to check if All exists in that array.


onSelectionChange(event) {

  const isSelectedAll = event.value.includes('All');

  if(isSelectedAll) {
    // Do select all logic 
  }
   
}

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