Angular - 响应式表单 - FormGroupName 内的 FormGroupName

Angular - Reactive Forms - FormGroupName inside FormGroupName

我有一个从 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 中,或者是否有更好的方法使用反应式实现相同的结果表格?

是的。 formGroupName 可以嵌套在另一个 formGroupName.

formGroupNameformControlName 属性通过在父 FormGroup.

中查找具有该特定名称的控件来工作

请注意,您的问题是因为您试图在 first FormGroup:

中找到名为 secondFormGroup
<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 的直接子项。在这种情况下确实存在。