gpt4 book ai didi

angular - 迭代 FormArray 以显示表单字段

转载 作者:行者123 更新时间:2023-12-04 15:07:28 24 4
gpt4 key购买 nike

我正在尝试使用响应式(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com