【问题标题】:How can I set maximum number of chips for mat-chip input?如何设置 mat-chip 输入的最大芯片数?
【发布时间】:2019-07-22 18:39:16
【问题描述】:

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

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

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

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

    退房 this 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);
      } 
    }
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 2021-10-11
      • 2018-08-12
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      相关资源
      最近更新 更多