如您所见,我有一个父表单组件和一个子组件。
{{myFormFather.value}} 显示nickName
值和name
值但不显示age
值。
{{myFormFather.status}} 它不识别子组件。就像我的 child 是一个幻影,为什么?
my-form-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
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
<div [formGroup]="ageForm">
<input formControlName="age">
</div>
my-form-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
演示 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));
}
关于javascript - Angular 中带有子组件的 react 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49063502/