首页 > 解决方案 > Angular:如何访问嵌套表单中控件的值

问题描述

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

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

在这两种情况下,我都可以使用 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);

在这些“名称”、“方式 1”、“方式 2”中,“方式 3”和“无获取”不起作用,因为它适用于“名称”

同样在 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}}

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

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

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

标签: angularangular-reactive-forms

解决方案


方式3应该没有数组

this.userForm.get('address.Country').value

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

this.userForm.controls.address.controls.Country.value

在模板中只是一个小错误。您应该拥有Country而不是country也可以通过.controls属性访问

{{userForm.controls.address.controls.country.value}}

推荐阅读