如何在FormArray(Reactive Forms)中使用mat自动完成(Angular Material auto



假设我有以下表单结构:

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;
}

名称控件应该是自动完成的,我如何将所有名称控件与自动完成列表关联起来?

我通过将FormArray内的每个name控件与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())
);
}

然后,每次我在form Array中构建formgroup(创建新项(后,我都需要在新索引处调用上面的函数,如下所示:

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);
}

在.html文件中,我们需要引用所需的filteredOption数组,我们可以使用i索引:

<mat-option *ngFor="let option of filteredOptions[i] | async " [value]="option">
{{ option.name }}
</mat-option>

请看这里的详细答案https://stackblitz.com/edit/angular-szxkme?file=app%2Fautocomplete-显示示例.ts

更新:要使用特定对象的默认值填充数组,可以使用以下接收表单:

let formGroup = this.fb.group({
name: [{value: { name: 'Mary' } , disabled: false}, [Validators.required]],
age: ['', [Validators.required]],
});

堆叠式

最新更新