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

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

问题描述

我正在尝试在控制台和 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 中类似:

Similarly in 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 应该没有数组

way 3 should be without array

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

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

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天全站免登陆