如何将Angular Material多选项目限制为N个项目? [英] How to limit Angular Material multiple select items to N items?

查看:23
本文介绍了如何将Angular Material多选项目限制为N个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

How to limit the number of items selected to N number? Where N is 3 or 4 or 5.

推荐答案

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

Set the selectionChange output event on the mat-select component, point it to your component function: (selectionChange)="changed()".

片段:

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

在您的组件中创建一个名为 mySelections 的全局变量.这将存储您的选择:) 它将保存一个字符串数组.

In your component create a global variable named mySelections. This will store your selections :) It will hold an array of strings.

看起来像这样:

mySelections: string[];

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

将数字 3 更改为 N 并快速完成.

Change the number 3 to N and presto, you're done.

这篇关于如何将Angular Material多选项目限制为N个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆