假设我具有以下表单结构:
this.myForm = this.formBuilder.group({
date: ['', [Validators.required]],
notes: [''],
items: this.initItems()
});
initItems() {
var formArray = this.formBuilder.array([]);
for (let i = 0; i < 2; i++) {
formArray.push(this.formBuilder.group({
name: ['', [Validators.required]],
age: ['', [Validators.required]],
}));
}
return formArray;
}
,并且名称控件应该是自动完成的,如何将所有名称控件与自动完成列表相关联?
答案 0 :(得分:4)
我通过将FormArray
中的每个filteredOption
控件与一个 ManageNameControl(index: number) {
var arrayControl = this.myForm.get('items') as FormArray;
this.filteredOptions[index] = arrayControl.at(index).get('name').valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this._filter(name) : this.options.slice())
);
}
数组相关联来解决了这个问题:
formgroup
然后,每次在form Array
内构建 addNewItem() {
const controls = <FormArray>this.myForm.controls['items'];
let formGroup = this.formBuilder.group({
name: ['', [Validators.required]],
age: ['', [Validators.required]],
});
controls.push(formGroup);
// Build the account Auto Complete values
this.ManageNameControl(controls.length - 1);
}
(创建新项目)后,我需要在新索引处调用上述函数,如下所示:
i
在.html文件中,我们需要引用所需的filteredOption数组,我们可以使用 <mat-option *ngFor="let option of filteredOptions[i] | async " [value]="option">
{{ option.name }}
</mat-option>
索引来做到这一点:
cv_products
请在此处查看详细答案https://stackblitz.com/edit/angular-szxkme?file=app%2Fautocomplete-display-example.ts