// Getter function:
get getCheckboxes_FormGroup()
{
return this.objFormGroup.controls.checkboxesBlogs.controls as FormArray;
}
ngOnInit()
{
this.objFormGroup = this.objFormBuilder.group(
{
checkboxesBlogs: new FormArray([])
}
)
for( var i = 0; i < this.blogs.length; i++)
{
// Generate a checkbox for this blog:
this.getCheckboxes_FormGroup.push( this.objFormBuilder.group(
{
blogTitle: [this.blogs[i].title],
blogId: [this.blogs[i].id],
checkboxValue: [false],
body: [this.blogs[i].body],
creationDate: [this.blogs[i].creationDate],
modificationDate:[this.blogs[i].modificationDate],
category: [this.blogs[i].category],
visible: [true]
}
)
);
}
}
在typescript中,我试图这样访问它。 this.getCheckboxes_FormGroup.controls[i].value.visible = false
这没有给我带来错误,但也没有将值设置为false。
在HTML中,我试图这样访问它。<div *ngFor = "let checkboxesBlog of getCheckboxes_FormGroup.controls; " >
<a *ngIf = "checkboxesBlog.controls.visible.value === true">
这不会给我带来错误,但它总是显示值为真。
在typecript和html中访问这个函数的合适方法是什么?
this.objFormGroup.controls.checkboxesBlogs.controls
不是一个FormArray(是一个FormGroups的数组)。
你想说的 this.objFormGroup.controls.checkboxesBlogs
但最好使用get()来获取控件。
get getCheckboxes_FormGroup()
{
return this.objFormGroup.get('checkboxesBlogs') as FormArray;
}
所以
this.getCheckboxes_FormGroup.at(i) //is the FormGroup.
this.getCheckboxes_FormGroup.at(i).get('visible') //is the FormControl
如果你需要改变值,你需要使用 "setValue"。
this.getCheckboxes_FormGroup.at(i).get('visible').setValue(true)
您也可以使用
this.objFormGroup.get('checkboxesBlogs.'+i+'.visible') //to get the control
this.objFormGroup.get('checkboxesBlogs.'+i+'.visible').setValue(true) //to change the value
在.html中,如果只想获得值
getCheckboxes_FormGroup.at(i).get('visible').value
//or
getCheckboxes_FormGroup.value[i].visible
//or
objFormGroup.value.checkboxesBlogs[i].visible'
//or
checkboxesBlog.value.visible //<--checkboxesBlog is the "variable" you loop
checkboxesBlog.get('visible').value //<--checkboxesBlog is the "variable" you loop
看你用 "value "来获取值,如果你获取表单的值,你需要 "穿过 "这个值,你可以获取数组或控件的值