Angular 6动态表单问题[第2部分] [英] Angular 6 Dynamic Forms issue [part 2]
问题描述
遵循 Angular 6动态表单问题的建议,我已经将我的应用制作为打印一个字段,但只有一个为空且有错误
Following recommendations from Angular 6 Dynamic Forms issue I've made my app to print one field out, but only one empty and with an error
错误 错误:找不到名称为"field0"的控件
ERROR Error: Cannot find control with name: 'field0'
我已将代码放在这里 https://stackblitz.com/edit/angular-mzu1ab
我正在按索引生成字段名称,因为我获取的数据不包含名称字段.
I'm generating field names by indices, since the data that I fetch contains no name fields.
推荐答案
之所以会发生这种情况,是因为您动态创建了表单控件名称,但实际上并没有将它们绑定到您的问题上.
This happens because you create your form control names dynamically, but you don't really bind them to your questions.
与其选择诸如field + i
之类的任意名称,不如绑定一个特定值.
Instead of chosing an arbitrary name like field + i
, you should instead bind on a specific value.
在此 stackblitz ,我将表单控件名称绑定到了标签,如您所见,它的工作原理就像是一种魅力.
In this stackblitz, I binded the form control names to the label, and as you can see, it works like a charm.
<input [formControlName]="question.label"
questsions.forEach((e, i) => {
if (e.type === 'string' || e.type === 'text' || e.type === 'list') {
group[e.label] = new FormControl(e.value, Validators.required);
这篇关于Angular 6动态表单问题[第2部分]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!