'How to limit Angular Material multiple select items to N items?

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.



Solution 1:[1]

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>

Solution 2:[2]

The best solution is based on only if you disable only unselected options. Otherwise it is meaningless because after you disable all options, then how is that possible to unselect any of options?

in HTML component:

<mat-form-field>
  <mat-select placeholder="Category" [formControl]="categories" multiple>
    <mat-option *ngFor="let cat of categoryArr" [value]="cat.id"
      [disabled]="isOptionDisabled(cat.id)">
      {{cat.title}}
    </mat-option>
  </mat-select>
</mat-form-field>

in controller:

isOptionDisabled(opt: any): boolean {
  return this.categories.value.length >= 3 && !this.categories.value.find(el => el == opt)
}

Now: Only already selected options are enable to do something, other options are disabled, as follows:

Only already selected options are enable to do something, other options are disabled

User can uncheck any of checked options so that user have chance to be able to do check/uncheck on the form field.

Solution 3:[3]

Here you go:

<mat-select placeholder="Toppings" [formControl]="toppings" (selectionChange)="selectionChanged(event)" multiple>

...

selectionChanged({ value }: MatSelectChange) {
  if (value.length >= 3) {
    this.formGroup.patchValue({
        toppings: value.slice(0, 3)
    });
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob
Solution 2 LuDeveloper
Solution 3 coturiv