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

后端 未结 2 965
情话喂你
情话喂你 2021-01-12 08:18

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.

相关标签:
2条回答
  • 2021-01-12 08:37

    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.

    0 讨论(0)
  • 2021-01-12 08:38

    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>
    
    0 讨论(0)
提交回复
热议问题