我正在尝试在 Angular 中构建表单数组。当数据未显示时,我将代码最小化以显示行为。我必须为最终代码使用表单数组。请帮助我度过这个难关。我正在使用 Angular 6。
为什么我会收到此错误:
错误:找不到名称为“resultOptions”的控件
// My component .ts file
import {FormControl, FormArray, FormBuilder, FormGroup} from '@angular/forms';
export class MyComponent implements OnInit, OnDestroy {
private resultForm: FormGroup;
private destroyed$: Subject<boolean> = new Subject();
resultData = [
{
text: 'My Text',
}];
constructor(private formBuilder: FormBuilder) {
this.resultForm = this.formBuilder.group({
childData: this.formBuilder.array([])
});
this.setMainOptions();
}
setMainOptions() {
const control = <FormArray>this.resultForm.controls.childData;
this.resultData.forEach(x => {
control.push(this.formBuilder.group({
text: new FormControl()}))
})
}
ngOnInit() {
}
ngOnDestroy() {
this.destroyed$.complete();
}
}
// my html
<form [formGroup]="resultForm">
<div formArrayName="resultOptions">
<div *ngFor="let mainOption of resultForm.get('childData').controls; let i=index">
<div [formGroupName]="i">
<input [formControlName]="text" />
</div>
</div>
</div>
</form>
<pre>{{resultForm.value | json}}</pre>
非常感激!