我试图在表单formgroup中添加动态字段,我需要在该表单组中的from数组中添加formarray,我已经尝试了但是我正在修改以下错误
error_handler.js:54 EXCEPTION:./AppComponent类中的错误AppComponent - 内联模板:6:16导致:无法读取属性' push'未定义的
请提前帮助我解决此问题
这是plunkr
Component.ts
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to: Selector(("setBackgroundColor"))) {
statusBar.backgroundColor = UIColor.magento
}
func setStatusBarBackgroundColor(color: UIColor) {
guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }
statusBar.backgroundColor = color
}
Component.html
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormArray, ReactiveFormsModule } from "@angular/forms";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public formGroupz: FormGroup;
constructor(private frmbldr: FormBuilder) { }
private fieldIdentifier: any;
items: any[] = [];
ngOnInit() {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
this.formGroupz = this.frmbldr.group({
main:this.frmbldr.array([this.initRules()])
})
}
initRules(){
return this.frmbldr.group({
ifgroup: this.frmbldr.array([]),
truegrp: this.frmbldr.array([]),
falsegrp: this.frmbldr.array([])
})
}
ifFields() {
debugger
return this.frmbldr.group({
conditionfields: ['']
})
}
initextraField() {
debugger
if (this.fieldIdentifier == "true") {
return this.frmbldr.group({
truefields: ['']
})
}
else if (this.fieldIdentifier == "false") {
return this.frmbldr.group({
falsefields: ['']
})
}
}
addiffields() {
debugger
this.fieldIdentifier = "if";
const control = <FormArray>this.formGroupz.controls['main']['controls']['ifgroup'];
const addrCtrl = this.ifFields();
control.push(addrCtrl);
}
addtruefields() {
debugger
this.fieldIdentifier = "true";
const control = <FormArray>this.formGroupz.controls['truegrp'];
const addrCtrl = this.initextraField();
control.push(addrCtrl);
}
addfalsefields() {
this.fieldIdentifier = "false";
const control = <FormArray>this.formGroupz.controls['falsegrp'];
const addrCtrl = this.initextraField();
control.push(addrCtrl);
}
}
答案 0 :(得分:2)
您收到此错误,因为您当前的结构如下所示:
formGroupz(FormGroup)
|----main(FormArray) <------- mention here main is FormArray
|----ifgroup(FormArray)
|----truegrp(FormArray)
|----falsegrp(FormArray)
如果您想访问sub formArray ifgroup
并且同样适用于truegrp
和falsegrp
,您可以通过以下语法使用formArray索引来实现它(模板的语法相同但没有{{1} }}):
this
还要确保您的模板与表单结构配对。
参考 Plunker Demo (固定模板表单结构)。
顺便说一句,如果你不需要第一层formArray,这里有一个更简单的 Plunker demo ,它将this.formGroupz.get('main').controls[0].get('ifgroup')
// or
this.formGroupz.controls.main.controls[0].controls.ifgroup
更改为main
。