I came up with a callback on the value change of the select, which then checks if the first selected option has no value and then resets the formControl (this solution is for reactive forms. It should be easy to adapt for model forms)
HTML:
<mat-select formControlName="myControl" multiple (ngModelChange)="resetSelect($event, 'myControl')">
<mat-option>Select All</mat-option>
<mat-option [value]="1">Option 1</mat-option>
<mat-option [value]="2">Option 2</mat-option>
<mat-option [value]="3">Option 3</mat-option>
</mat-select>
TS:
/**
* click handler that resets a multiple select
* @param {Array} $event current value of the field
* @param {string} field name of the formControl in the formGroup
*/
protected resetSelect($event: string[], field: string) {
// when resetting the value, this method gets called again, so stop recursion if we have no values
if ($event.length === 0) {
return;
}
// first option (with no value) has been clicked
if ($event[0] === undefined) {
// reset the formControl value
this.myFormGroup.get(field).setValue([]);
}
}
This works, but it feels a bit dirty. setValue() of course triggers ngModelChange, so we would go into a recursion, which I simply stop with $event.length === 0. Also, checking for the first option with a value of undefined seems a bit ... meeeeh...
I would appreciate if someone could provide a more elegant solution!
setValue()doesn't seem to check the boxes, so I'm currently taking a look at this approach: stackoverflow.com/questions/47183007/… - masterfloda