Angular:如何访问嵌套表单中控件的值

Ash*_*ish 2 angular angular-reactive-forms

我正在尝试在控制台和 HTML 中打印获取嵌套表单的表单控件的值。

userForm = new FormGroup({
    name: new FormControl("Tom Alter"),
    address: new FormGroup({
        Country: new FormControl("India"),
        State: new FormControl("Delhi")
    })
});
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都可以使用 get 语句找到值。

console.log ("name : ", this.userForm.controls.name.value);
console.log ("Country using Get Way 1  : ", this.userForm.get(['address', 'Country']).value) ;
console.log ("Country using Get Way 2 : ", this.userForm.get(['address']).get(['Country']).value);
console.log ("Country using Get Way 3 : ", this.userForm.get(['address.Country']).value);
console.log ("Country without Get: ", this.userForm.group.address.controls.cCountry.value);
Run Code Online (Sandbox Code Playgroud)

在这些“名称”中,“Way1”、“Way2”正在工作,但是“Way 3”和“Without get”不起作用,因为它适用于“name”

同样在 HTML 中:

Name : {{userForm.controls.name.value}}
<br>
<br>
Country with get Way - 1 : {{userForm.get(['address']).get(['Country']).value}}
<br>
Country with get Way - 2 : {{userForm.get(['address','Country']).value}}
<br>
<br>
Country without get: {{userForm.address.controls.country.value}}
Run Code Online (Sandbox Code Playgroud)

name 和 Way 1 工作正常,而“Way-2”和“Without get”则不起作用。

请指出我在代码中的错误。

代码可在https://stackblitz.com/edit/angular-nestedformgroups 上获得

And*_*rei 5

方式 3 应该没有数组

this.userForm.get('address.Country').value
Run Code Online (Sandbox Code Playgroud)

没有 Get 的国家可以通过控件访问

this.userForm.controls.address.controls.Country.value
Run Code Online (Sandbox Code Playgroud)

在模板中有一个小错误。你应该拥有Country而不是country通过.controls财产访问

{{userForm.controls.address.controls.country.value}}
Run Code Online (Sandbox Code Playgroud)