如何从Angular中的JSON响应在formArray中添加数据?
我有一个来自firebase的JSON响应,但当我加载页面时,它只显示formArray中的第一个数组,而不是多个字段。请检查我下面的代码,并指导我哪里错了 这是我从firebase得到的回复的快照 代码如何从Angular中的JSON响应在formArray中添加数据?,angular,typescript,angular-reactive-forms,angular-forms,Angular,Typescript,Angular Reactive Forms,Angular Forms,我有一个来自firebase的JSON响应,但当我加载页面时,它只显示formArray中的第一个数组,而不是多个字段。请检查我下面的代码,并指导我哪里错了 这是我从firebase得到的回复的快照 代码 ngOnInit(): void { this.loadForm(); this.questionService.getQuestion(this.id).subscribe((res) => { this.editQuestionForm.patchVa
ngOnInit(): void {
this.loadForm();
this.questionService.getQuestion(this.id).subscribe((res) => {
this.editQuestionForm.patchValue({
question: res.payload.data()['question'],
type: res.payload.data()['type'],
next_question: res.payload.data()['next_question'],
actions: res.payload.data()['actions'],
});
});
}
loadForm() {
this.editQuestionForm = this.fb.group({
question: ['', Validators.required],
type: ['', Validators.required],
actions: this.fb.array([this.createActionFields()]),
next_question: ['', Validators.required],
});
}
action_fields(): FormArray {
return this.editQuestionForm.get('actions') as FormArray;
}
createActionFields(): FormGroup {
return this.fb.group({
field: '',
response: '',
});
}
addActionFields() {
this.action_fields().push(this.createActionFields());
}
removeActionFields(index) {
this.action_fields().removeAt(index);
}
接下来就是输出
请检查我的上述代码,并指导我如何显示正确的数据。如果操作有响应,您需要在操作中设置与响应操作大小相同的控件 例如,如果由于使用
patchValue
而需要将5个字段的响应返回数组addActionFields()
五次,则不会出现错误,但如果使用setValue
则会看到错误
this.questionService.getQuestion(this.id).subscribe((res)=>{
const actions=res.payload.data()['actions'];
action.forEach(()=>{
这个.addActionFields();
});
this.editQuestionForm.patchValue({
问题:res.payload.data(),
类型:res.payload.data()['type'],
下一个问题:res.payload.data(),
行动
});
});