繁体   English   中英

Angular中具有组件子的反应形式

[英]reactive form with component child in Angular

正如您所看到的,我有一个父组件组件与组件子组件。 {{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]]
    });
}

嗨,你一直在寻找的解决方案

演示堆闪电战

问题是:您覆盖了从父级传递的表单组

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM