可能是因为在HTML中,mat-chip-input需要在MatChipList中使用。可使用以下代码解决:
HTML代码:
JavaScript代码:
import {Component, ViewChild, ElementRef} from '@angular/core'; import {MatChipInputEvent} from '@angular/material/chips'; import {COMMA, ENTER} from '@angular/cdk/keycodes';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { fruits: string[] = ['Apple', 'Banana', 'Lemon']; separatorKeysCodes: number[] = [ENTER, COMMA];
add(event: MatChipInputEvent): void { const input = event.input; const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(fruit: string): void { const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
} }