0
votes

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()

    }));
  }
}

2

2 Answers

0
votes

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

0
votes

Did you forgot to add parent FormGroup to viewProviders to your child component? Like this:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less'],
  viewProviders: [
    {
      provide: ParentComponent,
      useExisting: FormGroupDirective
    }
  ]
})