简体   繁体   中英

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.status}} it dont recognice the component child. Is like my child was a phantom, why?

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

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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