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
[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);
}
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.
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') {
// ...
}
});
}
}
<mat-select multiple #mySelect">
<!-- option here -->
</mat-select>