How to build form with multiple components in Angular 6?

Make the following changes

1.Use only one FormGroup instead of creating the new FormGroup for each component.

2.You have @Input for FormGroup however you are not passing as input.

3.Remove FormBuilder from the child component.

app.component.html

<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
    <app-names [myForm]="myForm"></app-names>
    <app-address [myForm]="myForm"></app-address>
    <app-phones [myForm]="myForm"></app-phones>
    <button type="submit">Submit</button>
</form>

address.component.ts

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

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

  @Input() myForm: FormGroup;
  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.myForm.addControl("homeAddress" , new FormControl());
    this.myForm.addControl("officeAddress" , new FormControl());
  }

}

Make the similar changes for other components.


There's another option to do it without using @Input

import { Component, OnInit } from '@angular/core';
import {
    FormControl,
    ControlContainer,
    FormGroupDirective
} from '@angular/forms';

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.css'],
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
     }
  ]
})
export class AddressComponent implements OnInit {
  constructor(private parent: FormGroupDirective) {}

  ngOnInit() {
    const myForm = this.parent.form;
    myForm.addControl("homeAddress", new FormControl());
    myForm.addControl("officeAddress", new FormControl());
  }
}