我有一个从API返回的嵌套JSON响应,它的结构与在模板上显示它的方式不同,例如:
@Component({
selector: 'reactive-form-example',
styles: ['./reactive-form-example.component.css'],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div formGroupName="first">
<input type="text" placeholder="some id" formControlName="someId">
<div formGroupName="second">
<input type="text" placeholder="some text" formControlName="someText">
</div>
</div>
</form>
`
})
export class ReactiveFormExampleComponent {
form = new FormGroup({
first: new FormGroup({
someId: new FormControl('587824')
}),
second: new FormGroup({
someText: new FormControl('the sky is blue')
})
});
onSubmit(value) {
console.log('Submit', this.form.value);
}
}
问题:是否有可能在另一个formGroupName
中嵌套formGroupName
,或者是否有更好的方法使用反应性表单来实现相同的结果?
发布于 2018-05-13 13:19:53
是。formGroupName
可以嵌套在另一个formGroupName
中。
formGroupName
和formControlName
属性通过在父FormGroup
中找到具有该特定名称的控件来工作。
请注意,您的问题是由于您试图在FormGroup
FormGroup中找到名为second
的first
而引起的:
<form [formGroup]="form">
<div formGroupName="first">
<div formGroupName="second">
</div>
</div>
</form>
要做到这一点,您必须按照以下方式调整您的模型,其中second
成为first
的子代
form = new FormGroup({
first: new FormGroup({
someId: new FormControl('587824'),
second: new FormGroup({
someText: new FormControl('the sky is blue')
})
}),
});
emostafa的建议之所以有效,是因为您要求form
实例在模型中获得一个名为second
的直接子级。在这种情况下是存在的。
https://stackoverflow.com/questions/50320307
复制相似问题