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:
protected resetSelect($event: string[], field: string) {
if ($event.length === 0) {
return;
}
if ($event[0] === undefined) {
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