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

Issue

This Content is from Stack Overflow. Question asked by Deepesh Kumar

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.

screenshot of mat-select with multiple options

<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);
}



Solution

Instead of using selectionChange(), you can subscribe to the optionSelectionChanges. Every time the selection is changed, it will be triggered.

Please don’t forget to unsubscribe when you subscribe to thing. I won’t include it here.

In example.component.ts


import { Component, ViewChild, AfterViewInit } from '@angular/core';

import { MatSelect } from '@angular/material/select';

@Component({
  //...
})
export class Example implements AfterViewInit {

  // get the view reference from the html called '#mySelect'
  @ViewChild('mySelect')
  mySelect: MatSelect;

  ngAfterViewInit() {

    // the view reference is only available after the view is initialized. 
    // That's why we have to subscribe in this hook.

    this.mySelect.optionSelectionChanges.subscribe(change => {
      const currentSelect = change.source.value;

      if(currentSelect === 'All') {
         // ... 
      }

    });
  }

}

In example.component.html

<mat-select multiple #mySelect">
  <!-- option here -->    
</mat-select>


This Question was asked in StackOverflow by Deepesh Kumar and Answered by skouch2022 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?