我的垫子芯片在大多数情况下都运行良好。它将所有芯片数据设置为我的表格控制值。但是,如果我键入一些内容,然后在输入框中取消/退格而不将其添加到芯片中,则它仅发送空字符串,而完全忽略所有芯片值。这是我的代码:
Component.html
<mat-form-field appearance="outline" fxFlex="100" class="label">
<mat-label><b>Fruits</b></mat-label>
<mat-chip-list #chipList aria-label="Fruit selection">
<mat-chip *ngFor="let fruit of fruits; let indx=index;"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(fruit, indx)">
{{fruit}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input
placeholder="Add Fruits"
#fruitInput
formControlName="fruitControl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let fruit of filteredFruits | async [value]="fruit.name">
{{fruit.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
component.ts(添加芯片功能)
add(event: MatChipInputEvent): void {
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim() && this.fruits.length < 2) {
this.fruits.push(value.trim());
input.value = '';
}
// Reset the input value
if (input) {
// input.value = '';
this.form.controls.fruitControl.setValue(this.fruits);
}
if(this.fruits.length > 2) {
this.chipList.errorState = true;
}
this.form.controls.fruitControl.setValue(this.fruits);
}
}
remove(fruit, indx): void {
this.fruits.splice(indx, 1);
if(this.fruits.length <= 2) {
this.chipList.errorState = false;
}
}
selected(event: MatAutocompleteSelectedEvent): void {
if (this.fruits.length < 2) {
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
}
}
component.ts(订阅和自动完成功能)
getFruits(): void {
this.service_.getAllFruits().subscribe(
res => {
this.fruitList = res;
});
this.filteredFruit = this.form.controls.fruitControl.valueChanges
.pipe(
startWith(''),
map(name => name ? this._filters(name) : this.fruitList.slice())
);
}
private _filters(value: any): any[] {
return this.fruitList.filter(fruit => fruit.name.toLowerCase().indexOf(value) === 0 && !this.fruits.find( existingFruit => existingFruit === fruit ));
}
使用stackblitz示例进行更新:
https://stackblitz.com/edit/angular-nzjugg?embed=1&file=src/app/app.component.html
尝试输入带有筹码的值,然后输入另一个值,而无需单击回车,以后您将在其中退格/取消键入。您可以在控制台中看到其将空字符串而不是芯片值推送到表单。