Angular:如何以嵌套形式访问控件的值 [英] Angular : How to access the value of controls in nested forms

查看:77
本文介绍了Angular:如何以嵌套形式访问控件的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Console以及HTML上打印获得嵌套表单的表单控件的值.

I am trying to print get the value of Form Controls of Nested form on Console as well as in HTML.

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

在两种情况下,我都可以使用get语句查找值.

In Both the cases, I am able to find the value using get statement.

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);

在这些名称"中,"Way1","Way2"有效,但是"Way 3"和"Without get"无效,因为它适用于"name"

Out of these "Name", "Way1", "Way2" are working but, "Way 3" and "Without get" is not working as it is working for "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}}

名称和方法1正常工作,而方法2"和没有得到"则不起作用.

name and Way 1 is working fine, where as "Way-2" and "Without get" is not working.

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

Please point me to my mistake in the code.

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

推荐答案

方法3应该没有数组

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

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

Country without Get can be accessed through controlls

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

在模板中只有一个小错误.您应该拥有Country而不是country,并且还可以通过.controls属性

in the template there is just a small mistake. you should have Country instead of country and also access through .controls propery

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

这篇关于Angular:如何以嵌套形式访问控件的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆