![](/img/trans.png)
[英]Angular Reactive Forms - Validation Errors - Cannot read property of undefined or null
[英]Angular reactive form *ngFor loop, cannot read 'property' of undefined
我正在尝试循环动态值以在我的表单上创建单选按钮项。 我设法显示了来自我的数据的三个单选按钮:
radiot: [
{
section: "yes",
sectionCode: "1"
},
{
section: "no",
sectionCode: "2"
},
{
section: "maybe",
sectionCode: "3"
}
]
问题是我无法显示“部分”选项。
例如
<div class="form-check-inline" *ngFor="let item of personal.radioButtons.radiot; let i = index">
<label for="yes" class="col-12 customradio"
><span>{{item[i].section}}</span>
<input value="{{item[i].section}}" id="{{item[i]}}" type="radio" [formControlName]="i"/>
<span class="checkmark"></span>
</label>
</div>
我究竟做错了什么? 收到错误 - Cannot read property 'section' of undefined
您不需要在 *ng 中使用i
,因为您已经在 position 处引用了 object。
因此,对于第一次迭代,您的item
将是
{
section: "yes",
sectionCode: "1"
}
所以你可以只做item.section
- 不需要索引 position。
<span>{{item.section}}</span>
将您的模板从[formControlName]更改为formControlName
<label for="{{item.section}}" class="col-12 customradio"
><span>{{item.section}}</span>
<input value="{{item.section}}" name="formGroupName" id="{{item.section}}" type="radio" formControlName="radiot"/>
<span class="checkmark"></span>
</label>
正如目前所写的那样,您告诉 angular 查找名为 radiot 的未定义变量,但它需要的是一个字符串,因此它可以在当前表单 object 上将其作为属性查找
你应该把=
而不是:
radiot = [
{
section: "yes",
sectionCode: "1"
},
{
section: "no",
sectionCode: "2"
},
{
section: "maybe",
sectionCode: "3"
}
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.