正如你所看到的,我有一个带有组件子元素的父表单组件。
{{myFormFather.value}}显示nickName
值和name
值,但不显示age
值。
{{myFormFather.status}}它不识别组件子。就像我的孩子是幻影,为什么?
我外形father.html
<form [formGroup]="myFormFather" (ngSubmit)="onSubmit()">
<input formControlName="nickName">
<input formControlName="name">
<my-form-child
[age]="myFormFather">
</my-form-child>
<button type="submit"
[disabled]="myFormFather.invalid">Save
</button>
</form>
我外形father.ts
myFormFather = new FormGroup({
nickName: new FormControl(),
name: new FormControl()
});
constructor(private fb:FormBuilder) {}
ngOnInit() {this.createForm()}
createForm() {
this.myFormFather = this.fb.group({
nickName: ['', [Validators.required],
name: ['', [Validators.required]
});
}
我外形child.html
<div [formGroup]="ageForm">
<input formControlName="age">
</div>
我外形child.ts
@Input() ageForm = new FormGroup({
age: new FormControl()
});
constructor(private fb:FormBuilder) {}
ngOnInit() {this.createForm()}
createForm() {
this.ageForm = this.fb.group({
age: ['', [Validators.required]]
});
}
答案 0 :(得分:3)
嗨,您一直在寻找的解决方案
问题是:您覆盖了从父
传递的表单组
@Input() ageForm = new FormGroup({
age: new FormControl()
});
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.createForm()
}
createForm() {
// This is overwriting the FormGroup passed from parent!
this.ageForm = this.fb.group({
age: ['', [Validators.required]]
});
// Instead you had to use
// this.ageForm.addControl("age", new FormControl('', Validators.required));
}