【发布时间】:2019-07-22 18:39:16
【问题描述】:
我想让用户在 mat-chip 中只输入一个芯片并自动完成。 我知道 md-chips 有 md-max-chips 来设置最大芯片数。 但是我正在使用 mat-chip,我该如何设置这样的最大芯片数?
<mat-chip-list maxLength="1">
:
:
</mat-chip-list>
【问题讨论】:
我想让用户在 mat-chip 中只输入一个芯片并自动完成。 我知道 md-chips 有 md-max-chips 来设置最大芯片数。 但是我正在使用 mat-chip,我该如何设置这样的最大芯片数?
<mat-chip-list maxLength="1">
:
:
</mat-chip-list>
【问题讨论】:
据我所知,您不能直接在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);
}
}
基本上,在添加任何新筹码之前,您会检查已选择的筹码数量。相应地编辑您的代码,上述示例应涵盖两种情况(自动完成和键入)。
【讨论】: