Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: Nested Reactive Form in sub-component not working

I'm using Angular 8 Nested Reactive Form in a child component, but it does not work. I have searched the official Angular documentation, but I can not find any example on this.

My solution is available at stackblitz.com. I'm unable to show companyName for each company and address details for each address. Any ideas?

According to Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017 it should be straight forward...

Her video Nested Forms in Angular between 35:31-36:51

In parent.component.html

<form [formGroup]="form">

    <div *ngFor="let address of addresses">
        <app-child [address]="address"></app-child>
    </div>

    <button type="submit">Save</button>

</form>

In parent.component.ts

export class ParentComponent implements OnInit {

  form = new FormGroup({});

  addresses : Address[] = [
    new Address("Street 1", "City 1"),
    new Address("Street 2", "City 2"),
    new Address("Street 3", "City 3"),
  ]

  constructor() { }

  ngOnInit() {
  }
}

In child.component.html

<div formGroupName="address">

     <input formControlName="street">
     <input formControlName="city">

</div>

In child.component.ts

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {

  @Input() address: Address;
  form: FormGroup;

  constructor(parent: FormGroupDirective) {
    this.form = parent.form;
  }

  ngOnInit() {
    this.form.addControl('address', new FormGroup({
      street: new FormControl()
      city: new FormControl()

    }));
  }
}

like image 937
CodeAlike Avatar asked Apr 11 '26 22:04

CodeAlike


1 Answers

Try passing your formGroup as input instead of using the constructor into the child component.

@Input() formGroup: FormGroup;

instead of

constructor(parent: FormGroupDirective) {
  this.form = parent.form;
}

Edited 02/15/2020

I changed some code and solved your issue. The solution is available here: https://stackblitz.com/edit/angular-vyaj57-kgkdih

like image 82
bjdose Avatar answered Apr 14 '26 12:04

bjdose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!