Angular reactive form - Getting error while passing formArray to child component

Viewed 1810

I have nested reactive form with formGroup and formArray in it.
When I tried to pass nested formArray to child component I am getting the below error as

FormArrayName must be used with a parent formGroup directive

Below is the parent form group

this.employeeForm= this.fb.group({
 employee: this.fb.group({
   name: [null],
   id: [null]
  }),
 address: this.fb.array({
   location: [null],
   city: [null]
 });
});

Parent Form component

<form [formGroup]="employeeForm">
  <app-address [address]="employeeForm.controls.address"></app-address>
</form>

Address child component html

<div [formArrayName]="address">
<div *ngFor="let item of address.controls;" [formGroupName]="i">
  <input type="text" formControlName="location">
</div>
</div>

Address child component ts

import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormArray } from '@angular/forms';


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

  constructor() { }
  @Input() address: FormArray;
  ngOnInit() {
  }

}

The overall form values are working fine when I did console.log(this.employeeForm)
Please check and suggest. Thanks for your kind help.

1 Answers

The code looks fine. The issue is where you are using a custom-component app-address for the child form-group.

Angular forms are not automatically registered when inside nested component. However you can workaround this by providing the outer FormGroup to the child component.

You should also be passing the formGroup instance along with control name to your custom component. And then create a form control under that formGroup in custom component. Your custom component will create the control virtually under the same formGroup that you have provided.

<app-address [address]="employeeForm.controls.identity" [formGroup]="yourFormGroup" [controlName]="controlName"></app-address>

In child component you can initialize the form:

ngOnInit() {
   let control: FormControl = new FormControl('', Validators.required);
   this.formGroup.addControl(this.controlName, control);
}
Related