angular - 如何设置mat-chip输入的最大芯片数?

标签 angular angular-material

我想让用户在自动完成的 mat-chip 中只输入一个芯片。 我知道 md-chips 有 md-max-chips 来设置最大芯片数。 但是我使用的是 mat-chip,如何设置这样的最大芯片数?

<mat-chip-list maxLength="1">
  :
  :
</mat-chip-list>

最佳答案

据我所知,您不能直接在MatChipList 上设置它。您可以做的是,为用户尝试添加的每个筹码自行检查所选筹码的数量,然后根据已添加的筹码数量决定是否添加筹码。

Check out this stackblitz taken from the official documentation and modified to solve your problem.

所有我改变的是这个(当通过自动完成添加筹码时):

selected(event: MatAutocompleteSelectedEvent): void {
  if (this.fruits.length < 1) { // <-- THIS
    this.fruits.push(event.option.viewValue);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  } 
}

还有这个(通过打字添加筹码时):

add(event: MatChipInputEvent): void {
  // Add fruit only when MatAutocomplete is not open
  // To make sure this does not conflict with OptionSelected Event
  if (!this.matAutocomplete.isOpen) {
    const input = event.input;
    const value = event.value;

    // Add our fruit
    if ((value || '').trim() && this.fruits.length < 1) { // <-- THIS
      this.fruits.push(value.trim());
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }

    this.fruitCtrl.setValue(null);
  }
}

基本上,在添加任何新筹码之前,您会检查已选择的筹码数量。相应地编辑您的代码,上面的示例应该涵盖这两种情况(自动完成和键入)。

关于angular - 如何设置mat-chip输入的最大芯片数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57138568/

相关文章:

angular - Mat-select 更改值不会通过双向绑定(bind)传播

angularjs - 将对象属性拆分为两列

angular - 如何以 Angular 从 toPromise() 获取值?

html - Angular NgFor 元素水平显示为标签

Angular 垫分隔器垂直宽度不调整

javascript - Angular 6 - MatDialog - EventEmitter - 将对象从 MatDialog 共享到父组件

angular - 如何禁用 Angular Material Expansion Panel 动画?

angular - 找不到模块 "@auth0/angular-jwt/"

angular - 即使未选择任何值,如何在表单中标记 ngbDatepicker 有效

angularjs - Angular 2 - 组件如何识别 URL 更改?