我试着用反应性的形式来做一些事情,但是很难实现我认为简单易懂的东西。
我想循环元素并将它们显示为窗体控件。
我目前有:
@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个文本字段,我需要对这段代码做些什么?
发布于 2021-01-22 19:38:51
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]
}));
});
}
}
发布于 2021-01-22 19:31:33
这里的问题是,您试图在questionForm.controls
上循环,这是不可迭代的,它是一个对象,它不是您所需要的,您也不需要重复表单数组,您需要在这个数组中的控件上循环
一个来自角基准的例子
<div formArrayName="cities">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i" placeholder="City">
</div>
</div>
因此,输入/控件需要有NgFor,循环应该在questions.controls
上。
https://stackoverflow.com/questions/65851307
复制相似问题