Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build form with multiple components in Angular 6?

I am trying to build Reactive-Form spanning multiple components, something like this

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

When I try to submit, I get empty object.

Stackblitz Here

like image 944
Shadab Mehdi Avatar asked Oct 14 '18 13:10

Shadab Mehdi


People also ask

Can you have multiple components in Angular?

Every component must be declared in one—and only one—Angular module. Open app.

What are the options to build forms in Angular 6?

Let us now create our form in the app. We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it. In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute.

What are dynamic forms in Angular?

A dynamic form requires an object model that can describe all scenarios needed by the form functionality. The example hero-application form is a set of questions —that is, each control in the form must ask a question and accept an answer. The data model for this type of form must represent a question.


1 Answers

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.

like image 161
Sunil Singh Avatar answered Nov 05 '22 22:11

Sunil Singh