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

sal*_*lly 2 angular-material angular

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

<mat-chip-list maxLength="1">
  :
  :
</mat-chip-list>
Run Code Online (Sandbox Code Playgroud)

Fab*_*üng 6

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

查看 stackblitz,取自官方文档并进行修改以解决您的问题。

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

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

这是(通过打字添加芯片时):

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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