angular - 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”不起作用。
请指出我在代码中的错误。
解决方案
方式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}}
推荐阅读
- java - XML 布局未出现在 R.layout 中
- api - 通过 GitHub API 获取所有私有仓库的名称
- botframework - 有没有一种干净的方式让机器人使用 Azure BotFramework 回复电子邮件线程?
- r - 应用 walk.forward 函数时出现 quantstrat 错误
- reactjs - 在生产模式下找不到 ReactJs Image
- javascript - 检测 CSS Modules/React 中不存在的类名的使用
- python - 覆盖 x 轴标签的 Python Dash 图图例
- lotus-notes - Lotus notes 从另一个不工作的集合中减去集合
- pandas - 将 covid 统计数据导入 pandas
- django - NameError:未定义名称“ProductTag”