嵌套表单,尝试将一个表单添加到另一个表单中,但收到错误“”Cannot read property“”addControl“of null”“。”“FormGroupDirective似乎没有返回父'form‘。正在尝试应用子窗体方法进行嵌套。
<p>
sub-forms-approach works!
</p>
<form [formGroup]="form">
<!--<input formControlName="name">-->
<app-sub-forms-approach-child-one></app-sub-forms-approach-child-one>
</form>
state: {{form.status}}
data: {{ form.value | json}}
父组件
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from
'@angular/forms';
@Component({
selector: 'app-sub-forms-approach',
templateUrl: './sub-forms-approach.component.html',
styleUrls: ['./sub-forms-approach.component.css']
})
export class SubFormsApproachComponent implements OnInit {
form= new FormGroup({
});
constructor() {
}
ngOnInit() {
}
}
子窗体HTML
sub-forms-approach-child-one works!
<div formGroupName='address'>
<input formControlName="pin">
<input formControlName="street">
</div>
子窗体组件
import { Component, OnInit } from '@angular/core';
import { ControlContainer, FormGroupDirective, FormControl, FormGroup}
from '@angular/forms';
@Component({
selector: 'app-sub-forms-approach-child-one',
templateUrl: './sub-forms-approach-child-one.component.html',
styleUrls: ['./sub-forms-approach-child-one.component.css'],
viewProviders: [
{provide: ControlContainer,
useExisting: FormGroupDirective
}
]
})
export class SubFormsApproachChildOneComponent implements OnInit {
form;
constructor(parent: FormGroupDirective) {
this.form = parent.form;
console.log(parent.form);
}
ngOnInit() {
this.form.addControl('address', new FormGroup({
pin: new FormControl(),
street: new FormControl()
}))
}
}
发布于 2018-04-22 19:01:12
由于@Input form
属性尚未初始化,因此无法在构造函数中获取FormGroupDirective.form
。Angular在创建节点时首先实例化组件类,然后才初始化输入属性。
所以把你的代码移到ngOnInit
钩子上:
constructor(private parent: FormGroupDirective) {}
ngOnInit() {
this.form = this.parent.form;
this.form.addControl('address', new FormGroup({
pin: new FormControl(),
street: new FormControl()
}))
}
发布于 2021-12-01 05:37:39
在没有包装窗体组的情况下使用输入属性formControlName="mainForm"
时,出现了相同的错误
https://stackoverflow.com/questions/49969472
复制相似问题