prajeesh
prajeesh

Reputation: 2382

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?

Upvotes: 2

Views: 3625

Answers (2)

santosh singh
santosh singh

Reputation: 28652

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 {}

Upvotes: 4

Samuel Shyu
Samuel Shyu

Reputation: 151

There are different ways to do this. You can see the angular document on component interaction at https://angular.io/guide/component-interaction In your case, one easy way is to use ViewChild.

 @ViewChild(BasicInfoComponent)
  private basicInfoComponent: BasicInfoComponent;
 @ViewChild(ContactInfoComponent)
  private contactComponent: ContactInfoComponent;
 @ViewChild(OrderInfoComponent)
  private orderComponent: OrderInfoComponent;

Then in the button click, you can access the data in those child components.

Upvotes: 0

Related Questions