我正在尝试使用响应式(Reactive)形式进行一些操作,但很难实现我认为很简单的内容。
我想遍历元素并将它们显示为表单控件。
我目前有:
@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]
}));
});
}
}
关于angular - 迭代 FormArray 以显示表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65851307/