遍历FormArray以显示表单字段



我正在尝试使用响应式表单,但是很难实现我认为会很简单的东西。

我想循环遍历元素并将它们显示为表单控件。

我现在有:

@Component({
selector: 'app-reactive-form-test',
styleUrls: ['./reactive-form-test.component.scss'],
template: `
<form [formGroup]="questionForm">
<ng-container formArrayName="questions" *ngFor="let question of questionForm.controls; let i = index">
<input type="text" formControlName="i">
</ng-container>
</form>
`
})
export class ReactiveFormTestComponent implements OnInit {
questionForm: FormGroup;
questions: ScheduledQuestionInterface[];
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.questionForm = this.fb.group({
questions: this.fb.array([])
});
this.questions = [];
this.questions.push(new ScheduledQuestion(1, 1, 1, 1));
this.questions.push(new ScheduledQuestion(2, 3, 1, 2));
this.questions.push(new ScheduledQuestion(3, 4, 1, 3));
this.questions.forEach(value => {
const control = this.questionForm.get('questions') as FormArray;
control.push(this.fb.group({
id: [value.id],
deliveryDateTime: [value.deliveryDateTime]
}));
});
}
}

现在我得到以下错误:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays..

我需要对这段代码做些什么来简单地显示3个ScheduledQuestion对象的3个文本字段?

questionForm.controls是一个对象,关键字作为formControls,基本上在你的情况下

{
questions: []
}

你试图遍历上述不可迭代的对象,因此出现错误

下面应该可以

@Component({
selector: 'app-reactive-form-test',
styleUrls: ['./reactive-form-test.component.scss'],
template: `
<form [formGroup]="questionForm">
<ng-container formArrayName="questions">
<ng-container *ngFor="let question of questionControls.controls; let i = index">
<input type="text" [formGroupName]="i">
</ng-container>

</ng-container>
</form>
`
})
export class ReactiveFormTestComponent implements OnInit {
questionForm: FormGroup;
questions: ScheduledQuestionInterface[];
get questionControls() {
return this.questionForm.get('questions') as FormArray;
}

constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.questionForm = this.fb.group({
questions: this.fb.array([])
});
this.questions = [];
this.questions.push(new ScheduledQuestion(1, 1, 1, 1));
this.questions.push(new ScheduledQuestion(2, 3, 1, 2));
this.questions.push(new ScheduledQuestion(3, 4, 1, 3));
this.questions.forEach(value => {
const control = this.questionForm.get('questions') as FormArray;
control.push(this.fb.group({
id: [value.id],
deliveryDateTime: [value.deliveryDateTime]
}));
});
}
}

这里的问题是你正在尝试循环questionForm.controls,它不是可迭代的,它是一个对象,它不是你需要的,你也不需要重复表单数组,你需要循环这个数组中的控件

来自Angular参考中的一个例子:

<div formArrayName="cities">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i" placeholder="City">
</div>
</div>

所以,你需要为你的输入/控制设置NgFor,并且循环应该在questions.controls

之上

最新更新