Reactive Forms
- import { FormGroup, FormArray , FormControl, FormBuilder } from '@angular/forms';
FormArray is similar to an array. We can push the new items into it and loop throughout items to append in HTML.
Sometimes, we need to give control creation logic to the end users as per their capabilities and skills or experience.
For example (Degrees)
- Raj – BCA
- Annu – B.Tech, MS
Therefore, we need an additional field as per the qualification and experience. In this demo, I’m creating additional fields for education and other fields by clicking on “Add Other Details”. This is a continuation of my last blog on Angular version 7.
This is a basic form with some fields with "Add Other Details" button. In this below screen, I clicked "Add other details" and it generated the same fields to capture additional details as below.
Let's see the "Add Other Details" ClickEvent.
Step 1
Create a personal details form on initialization.
- ngOnInit() {
- this.personalForm = this.formBuilder.group({
- firstName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(8)]],
- lastName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(8)]],
- address: ['', [Validators.required]],
- other: this.formBuilder.array([ this.addOtherSkillFormGroup()])
- });
- }
Step 2
Create a method which returns control objects.
- addOtherSkillFormGroup(): FormGroup {
- return this.formBuilder.group({
- education: ['', Validators.required],
- age : ['', Validators.required],
- degree: ['Bachelor', Validators.required]
- });
- }
Step 3
Here is the button click event code.
- addButtonClick(): void {
- (<FormArray>this.personalForm.get('other')).push(this.addOtherSkillFormGroup());
- }
Step 4
This code contains the HTML changes to loop a FormArray,
- <div style="background-color: gainsboro">
- <div class="form-group">
- <div class="col-md-offset-2 col-md-4">
- <button type="button" class="btn btn-primary" (click)="addButtonClick()">
- Add Other Details
- </button>
- </div>
- </div>
- <div formArrayName="other" *ngFor="let other of personalForm.get('other').controls; let i = index" class="form-group">
- <div [formGroupName]="i">
- <div class="form-group" class="row cols-md-12">
- <label class="col-sm-2 control-label" for="education">
- Other
- </label>
- <div class="col-sm-4">
- <input type="text" class="form-control" id="education" placeholder="Education" formControlName="education">
- </div>
- <div class="col-sm-4">
- <input type="text" placeholder="Age" class="form-control" formControlName="age">
- </div>
- </div>
- <br>
- <div class="form-group" class="row cols-md-12">
- <label class="col-md-2 control-label">Degree Type</label>
- <div class="col-md-8">
- <label class="radio-inline">
- <input id="degree" type="radio" value="Bachelor" formControlName="degree">Bachelor
- </label>
- <label class="radio-inline">
- <input id="degree" type="radio" value="Master" formControlName="degree">Master
- </label>
- </div>
- </div>
- </div>
- </div>
- </div>