angular - 无法在 FormArray 上进行迭代
问题描述
我使用的方法 -- formGroup -- -- FormControl -- , -- FormArray -- ------ -- FormControlList --
我也在嵌套的表单组中尝试过 FormArray
但我无法迭代表单数组,请让我知道方法是否正确。
HTML 错误——:对象可能为“空”——控件
代码 -
HTML --
<form [formGroup]="abcForm">
<section>
<div formArrayName="title">
<ul>
<li *ngFor="let control of abcForm.get('title').controls; let i= index;">
{{i}}
</li>
</ul>
</div>
</form>
///////////////////
TS --
titles: any = [
{
name: "one",
value: "one",
selected: false
},
{
name: "two",
value: "two",
selected: true
},
{
name: "three",
value: "three",
selected: true
},
];
constructor(private fb: FormBuilder)
this.abcForm = this.fb.group({
one: ['',Validators.required],
title:
this.buildTitleControls()
,
});
buildTitleControls() {
const arr = this.titles.map((val : any) => {
return this.fb.control('');
});
return this.fb.array(arr);
}
解决方案
您必须添加?
到abcForm.get('title')
.
<li *ngFor="let control of abcForm.get('title')?.controls; let i= index;">