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

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

问题描述

在使用 https://material.angular.io/components/select/Overview#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天全站免登陆