复选框的动态FormArray [英] Dynamic FormArray for checkboxes
问题描述
我用angular2和Typescript构建一个Form. 我尝试动态添加复选框列表,但对我不起作用,我的错误在哪里?
I build a Form in angular2 and typescript. I try to add a list of checkboxes dynamically and it's not working for me, Where is my mistake?
模板代码:
<div formArrayName="categories">
<div class="form-group" *ngFor="let category of updateDetailsForm.controls.categories.controls; let i = index">
<label>
<input type="checkbox" formControlName="{{i}}">
{{category.name}}
</label>
</div>
</div>
打字稿代码:
updateDetailsForm: FormGroup;
private categories : Category[] = []
constructor(private router: Router,
private ss : SearchService,
private formBuilder: FormBuilder)
{
this.initForm() // before the categories loaded
this.ss.getAllCategories().subscribe(
data => {
this.categories = data
this.initForm() // refresh the form with categories
}
)
}
initForm() {
let allCategories: FormArray = new FormArray([]);
for (let i = 0; i < this.categories.length; i++) {
allCategories.push(
new FormGroup({
'name': new FormControl([this.categories[i].categoryName])
})
)
}
this.updateDetailsForm = this.formBuilder.group({
'image' : [''],
'categories': allCategories
})
}
这是我的UI结果,并且出现以下错误:
This is my UI result, and I get the following error:
嵌入式模板:17:33由以下原因引起:control.registerOnChange不是函数"
"inline template:17:33 caused by: control.registerOnChange is not a function"
复选框的数量正确,但是缺少文本,我无法通过用户选择来更新表单结果.
The number of checkboxes is correct but the text is missing and I can't update the form result with user selection.
-
错误是什么意思?
What the error means?
如何在复选框旁边插入正确的文本?
How can I insert the right text next the checkbox?
如何将用户选择更新为表单值?
How can update the user selection into the form value?
推荐答案
您已经以如下方式构建了表单模型:我们需要访问您推送到数组中的每个FormGroup
,然后访问内的命名控件:
You've built out your form model in such a way that we'll need to access each FormGroup
that you pushed onto the array and then access the named control within:
<span formGroupName="{{i}}">
<input type="checkbox" formControlName="{{category.name}}">
{{category.name}}
</span>
我们还需要调整如何推入值,以便名称是唯一设置的,而不是始终设置为"name"
:
We'll also need to tweak how we're pushing values so that the name is set uniquely instead of always set as "name"
:
let fg = new FormGroup({});
fg.addControl(this.categories[i].name, new FormControl(false))
allCategories.push(fg)
这里有个演示它的工具: http://plnkr.co/edit/OTiqwr1oCb8uEThQyDHx p =预览
Here's a plunker to demo it: http://plnkr.co/edit/OTiqwr1oCb8uEThQyDHx?p=preview
这篇关于复选框的动态FormArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!