首页 > 解决方案 > 如何将 Angular Material 多选项目限制为 N 个项目?

问题描述

在使用https://material.angular.io/components/select/overview#multiple-selection

如何将选择的项目数限制为 N 个?其中 N 为 3 或 4 或 5。

标签: angularangular-material2

解决方案


在组件上设置selectionChange输出事件,将mat-select其指向您的组件函数:(selectionChange)="changed()".

片段:

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

在您的组件中创建一个名为mySelections. 这将存储您的选择:) 它将包含一个字符串数组。

它看起来像这样:

mySelections: string[];

changed() {
  if (this.toppings.value.length < 3) {
    this.mySelections = this.toppings.value;
  } else {
    this.toppings.setValue(this.mySelections);
  }
}

将数字 3 更改为 N,然后就完成了。


推荐阅读