Search code examples
javascriptangularangular4-forms

Angular 4 - Form with multiple components - Submit data


I am new to angular 4.

I have a page that contains 3 sections. These sections are created as individual forms

section 1 - Basic information

first name
last name
email

section 2 - Contact information

address
city
state
zip

section 3 - Order Information

Order id
Item name
quantity 

These sections are divided into different components - BasicInfoComponent, ContactInfoComponent, OrderInfoComponent.

How to submit all these component data on a single button click?


Solution

  • With model-driven form this can be achieved quite easily.I have created a simple application in Demo.

    //our root app component
    import {Component, NgModule, Input} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import {FormsModule, ReactiveFormsModule} from '@angular/forms';
    import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      template: `
    
        <h3>Nested FormGroup</h3>
    
        <form [formGroup]="myForm">
          <label>Name: </label>
          <input formControlName="name" />
          <app-child [address]="myForm.controls.address"></app-child>
        </form>
        <br>
        <pre>Form Values: {{myForm.value | json}}</pre>
      `,
    })
    export class App {
    
      myForm: FormGroup
    
      constructor(private fb: FormBuilder) {}
    
      ngOnInit() {
        this.myForm = this.fb.group({
          name: [''],
          address: this.fb.group({
            street: [''],
            zip: ['']
          })
        })
      }
    
    
    }
    
    @Component({
      selector: 'app-child',
      template: `
    
        <div [formGroup]="address">
        <label>Street: </label>
          <input formControlName="street"><br>
        <label>Zip: </label>
          <input formControlName="zip">
        </div>
    
      `,
    })
    export class AppChild {
    
      @Input() address: FormGroup;
    
    }
    
    @NgModule({
      imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
      declarations: [ App, AppChild ],
      bootstrap: [ App ]
    })
    export class AppModule {}