针对这个问题,我们可以使用Angular的FormControl来进行实现。
首先,在组件类中定义一个FormControl:
export class AppComponent {
chips = ['Red', 'Green', 'Blue'];
myControl = new FormControl('', [Validators.required]);
addChip(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
this.chips.push(value.trim());
}
if (input) {
input.value = '';
}
}
removeChip(chip: string): void {
const index = this.chips.indexOf(chip);
if (index >= 0) {
this.chips.splice(index, 1);
}
}
}
然后,在模板中进行绑定:
{{chip}}
cancel
这样会保证只允许添加一个chip,并且输入框一直是可用的状态。如果需要限制多个chip的添加,我们可以在addChip()方法中进行处理。
例如,我们想要限制最多只能添加两个chip,而且一旦添加达到上限后,输入框需禁用,我们可以改写addChip()方法:
addChip(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
if (this.chips.length < 2) {
this.chips.push(value.trim());
}
if (this.chips.length === 2) {
上一篇:Angular-如何为数据检索使用多个patchvalues
下一篇:Angular-如何修复Schema验证失败,出现以下错误:数据路径.builders['app-shell']应该具有必需的属性class?