0
votes

I am trying to create a reactive form and below is a prototype of it.

enter image description here

I have to create 3 reactive forms Form1, Form2, Form3 and then club them into single reactive form say SignUpForm. It's like SignUpForm is an array of 3 different reactive forms. I Googled FormBuilder, FormArray and FormGroup but got all confused.

2
I still don't have minimum reputation to use embedded images in the post. Sorry for the inconvenience caused.Pranjal Successena
Check my repository, i am new in Angular but i created a reactive form with second levels to formGroup - github.com/Cuchu/dynamic-reactive-formMaxi Schvindt

2 Answers

1
votes

Create each of the three forms - Form1, Form2 and Form3 using FormBuilder:

form1group = this._formBuilder.group({
// Your formControls go here
})

Then create a SignUpForm containing these three formgroups (form1group, form2group and form3group).

signupForm = this._formBuilder.group({
    form1group,
    form2group,
    form3group
})

FormArray is an array of FormControls you should use when dealing with dynamic forms (i.e. when new FormControls are required to be added to form dynamically).

1
votes

you should use FormArray,First, on top of your other form imports, you’ll want to import FormArray from the Angular forms module:

app.component.ts

import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
signUpForm: FormGroup;
items: FormArray ;

ngOnInit() {
  this.signUpForm = this.formBuilder.group({
    formName: '',
    formDescription: '',
    items: this.formBuilder.array([ this.createItem() ])
  });
   this.addItem()
   this.addItem();
}

createItem(): FormGroup {
  return this.formBuilder.group({
    field1: '',
    field2: ''
  });
}

addItem(): void {
  this.items = this.signUpForm.get('items') as FormArray;
  this.items.push(this.createItem());
}

in html:

<div formArrayName="items"
  *ngFor="let item of signUpForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="field1" placeholder="field1">
    <input formControlName="field2" placeholder="field1">
  </div>
</div>

Now it’s as simple as calling our addItem method in our template when the user clicks to add a new item or do it in our component.