如何限制Angular Material多个select项为N项?

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

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

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

mat-select 组件上设置 selectionChange 输出事件,将其指向您的组件函数:(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,很快,大功告成。

您可以在垫子选项上使用禁用的 属性 来执行此操作,如下所示:

<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>

最好的解决方案是基于仅禁用未选择的选项。否则是没有意义的,因为你禁用了所有选项之后,怎么可能取消任何选项?

在 HTML 组件中:

<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>

在控制器中:

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

现在:只启用已经选择的选项做某事,其他选项禁用,如下:

用户可以取消选中任何选中的选项,以便用户有机会能够在表单字段上执行 check/uncheck。

给你:

<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)
    });
  }
}