[英]reactive form with component child in Angular
As you can see I have a father form component with a component child. 正如您所看到的,我有一个父组件组件与组件子组件。 The {{myFormFather.value}} show me nickName
value and name
value but dont show age
value. {{myFormFather.value}}显示nickName
值和name
值,但不显示age
值。 {{myFormFather.status}} it dont recognice the component child. {{myFormFather.status}}它不识别组件子。 Is like my child was a phantom, why? 就像我的孩子是幻影一样,为什么?
my-form-father.html 我的外形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>
my-form-father.ts 我的外形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]
});
}
my-form-child.html 我的外形child.html
<div [formGroup]="ageForm">
<input formControlName="age">
</div>
my-form-child.ts 我的外形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]]
});
}
Hi, the solution you have been looking for 嗨,你一直在寻找的解决方案
Demo Stack Blitz 演示堆闪电战
Problem was: You overwrote the form group being passed from the parent 问题是:您覆盖了从父级传递的表单组
@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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.