角-反应形式-FormGroupName内的FormGroupName

Jor*_*vis 3 angular angular-reactive-forms

我有一个从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);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:是否有可能formGroupName嵌套在另一个对象中formGroupName,或者是否有更好的方法使用反应形式来实现相同的结果?

Dav*_*ots 5

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

formGroupNameformControlName属性通过在父级中查找具有特定名称的控件来工作FormGroup

请注意,您的问题是由于尝试在FormGroup中查找FormGroup命名secondfirst引起的:

<form [formGroup]="form">
    <div formGroupName="first">
        <div formGroupName="second">
        </div>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

要使该工作正常进行,您必须按照以下方式调整模型,其中second的子模型为first

form = new FormGroup({
    first: new FormGroup({
        someId: new FormControl('587824'),
        second: new FormGroup({
            someText: new FormControl('the sky is blue')
        })
    }),        
});
Run Code Online (Sandbox Code Playgroud)

emostafa的建议之所以起作用,是因为您要求form实例second在模型中获得直接命名的子代。在这种情况下确实存在。