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

后端 未结 2 996
情话喂你
情话喂你 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:

    
    

    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.

提交回复
热议问题