我不确定 dom 引用变量 #chiplist 是问题所在。看起来 matChipList 由 typesOptions 数组支持,但你只有一个数组。因此,每次添加 matChipList 组件时,它仍然由与所有其他组件相同的数组支持。您需要有一个 typesOptions 数组,一个数组的数组。然后,当您 addItem 时,您还将一个新的子数组推送到 typesOptions (并类似地为removeItem 删除一个子数组)。
我还没有对此进行编码,只是通过查看代码提出的建议。
编辑 - 根据 James 的 stackblitz 编写了一个解决方案。
https://stackblitz.com/edit/angular-3od6rd-jkidxf
注意我还没有详细研究删除变体如何结合在一起,理想情况下我可能想使用键/值对来跟踪变体选项,使用 dom 输入元素 id 作为键(位于 MatChipInputEvent 中) ,而不是依赖于外循环索引。
stackblitz 中的一些代码:
export class ChipsOverviewExample {
productGroup: FormGroup;
variantsArray: FormArray;
typesOptionsArray: string[][] = [];
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.productGroup = this.fb.group({
name: '',
variants: this.fb.array([
this.fb.group({
type: '',
options: ''
})
]),
});
this.typesOptionsArray.push([]);
}
saveProduct(form: FormGroup) {
console.log(form);
}
// Add new item to FormArray
addItem(): void {
this.variantsArray = this.productGroup.get('variants') as FormArray;
this.variantsArray.push(this.fb.group({
type: '',
options: ''
}));
this.typesOptionsArray.push([]);
}
removeItem(index: number) {
this.variantsArray.removeAt(index);
}
addOpt(event: MatChipInputEvent, index: number): void {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.typesOptionsArray[index].push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
}
removeOpt(opt: string, index: number): void {
const optIndex = this.typesOptionsArray[index].indexOf(opt);
if (optIndex >= 0) {
this.typesOptionsArray[index].splice(optIndex, 1);
}
}
}