In using https://material.angular.io/components/select/overview#multiple-selection
How to limit the number of items selected to N number? Where N is 3 or 4 or 5.
Set the selectionChange
output event on the mat-select
component, point it to your component function: (selectionChange)="changed()"
.
snippet:
<mat-select placeholder="Toppings" [formControl]="toppings" (selectionChange)="changed()" multiple>
In your component create a global variable named mySelections
. This will store your selections :) It will hold an array of strings.
It looks like this:
mySelections: string[];
changed() {
if (this.toppings.value.length < 3) {
this.mySelections = this.toppings.value;
} else {
this.toppings.setValue(this.mySelections);
}
}
Change the number 3 to N and presto, you're done.
You can do this using the disabled property on the mat-option like so:
<mat-select formControlName="myCtrl" multiple>
<mat-option [disabled]="formGroup.get('myCtrl').value?.length > 2 && !formGroup.get('myCtrl').value?.includes(o)"
*ngFor="let o of itemList"
[value]="o">{{o.name}}
</mat-option>
</mat-select>