In this post, I will demonstrate how to add input elements dynamically to a form while building a Résumé Builder form.

It is very common to find web apps that have an input form to be filled by users who want to build their CVs online. Therefore, it is quite important for the user to be able to add as many experience blocks as needed in a dynamic way. And here the power of Angular Reactive Forms appears.

This is how our form will look like:

Adding a new “Experience Block” dynamically when clicking the add button

If you want to check the full code, you can check this Github repo .

Here are the steps to implement this form:

1. Firstly, we need to import ReactiveFormsModule from @angular/forms and then add it to the imports array in our NgModule. Here our app is simple so we only have one module which is the AppModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { ResumeBuilderComponent } from './resume-builder/resume-builder.component';
@NgModule({
declarations: [AppComponent, ResumeBuilderComponent],
imports: [BrowserModule, ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}

2. We will implement our form in the “ResumeBuilderComponent”

  • Add the required imports from ‘@angular/forms’
  • Declare our FormGroup
  • We will generate the different form controls using the FormBuilder service because it makes the code simpler. We need to inject it into the constructor first and add the required import.
...
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
@Component({
     ...
})
export class ResumeBuilderComponent implements OnInit {
resumeBuilderForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.resumeBuilderForm = this.formBuilder.group({
      firstName: ['', [Validators.required]],
      lastName: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phone: '',
      experienceBlocks:this.formBuilder.array(
                       [this.buildExperienceBlock()])
});
}
buildExperienceBlock(): FormGroup {
return this.formBuilder.group({
   title: ['', [Validators.required]],
   company: ['', [Validators.required]],
   location: ['', [Validators.required]],
   startDate: ['', [Validators.required]],
   endDate: ['', [Validators.required]],
   description: ['', [Validators.required]]
});
}
...
  • As you can see from the code above, we generated a Form Group in the ngOnInit Life Cycle Hook, it consists of simple child Form Controls ( firstName , lastName, email, and phone). But it contains a more complex control at the end which is the “experienceBlocks” Form Array. The child of this Form Array is an array of Form Groups.
  • The creation of each inner Form Group is handled to the function buildExperienceBlock(). We called this function once during the initialization phase to initialize the experienceBlocks Form Array with one experience block as a start.

3. We can easily now add a new experience block when the user clicks the add experience button as follows:

addExperience() {
 this.experienceBlocks.insert(0, this.buildExperienceBlock()); 
}

4. Lastly, we should loop through the Form Array in our template using *ngFor directive as follows:

<form (ngSubmit)="save()" [formGroup]="resumeBuilderForm">
....
 <div formArrayName="experienceBlocks" *ngFor="let experience of
  experienceBlocks.controls; let i = index">
   <div [formGroupName]="i">
     <label attr.for="{{ 'titleId' + i }}">Title</label>
     <input 
        id="{{ 'titleId' + i }}" 
        type="text"
        placeholder="Ex: Software Engineer"
        formControlName="title"/>
        ....
   </div>
  </div>
...
</form>

I hope you found this article useful!

featured_image
About the Author

Rasha Essam

Software Engineer at Andela

Thanks for subscribing!

 

More Insights

April 6, 2020

How to Build a Résumé Builder Using Angular Reactive Forms

Rasha Essam

In this post, I will demonstrate how to add input elements dynamically to a form while building a Résumé Builder form.

It is very common to find web apps that have an input form to be filled by users who want to build their CVs online. Therefore, it is quite important for the user to be able to add as many experience blocks as needed in a dynamic way. And here the power of Angular Reactive Forms appears.

This is how our form will look like:

Adding a new “Experience Block” dynamically when clicking the add button

If you want to check the full code, you can check this Github repo .

Here are the steps to implement this form:

1. Firstly, we need to import ReactiveFormsModule from @angular/forms and then add it to the imports array in our NgModule. Here our app is simple so we only have one module which is the AppModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { ResumeBuilderComponent } from './resume-builder/resume-builder.component';
@NgModule({
declarations: [AppComponent, ResumeBuilderComponent],
imports: [BrowserModule, ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}

2. We will implement our form in the “ResumeBuilderComponent”

  • Add the required imports from ‘@angular/forms’
  • Declare our FormGroup
  • We will generate the different form controls using the FormBuilder service because it makes the code simpler. We need to inject it into the constructor first and add the required import.
...
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
@Component({
     ...
})
export class ResumeBuilderComponent implements OnInit {
resumeBuilderForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.resumeBuilderForm = this.formBuilder.group({
      firstName: ['', [Validators.required]],
      lastName: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phone: '',
      experienceBlocks:this.formBuilder.array(
                       [this.buildExperienceBlock()])
});
}
buildExperienceBlock(): FormGroup {
return this.formBuilder.group({
   title: ['', [Validators.required]],
   company: ['', [Validators.required]],
   location: ['', [Validators.required]],
   startDate: ['', [Validators.required]],
   endDate: ['', [Validators.required]],
   description: ['', [Validators.required]]
});
}
...
  • As you can see from the code above, we generated a Form Group in the ngOnInit Life Cycle Hook, it consists of simple child Form Controls ( firstName , lastName, email, and phone). But it contains a more complex control at the end which is the “experienceBlocks” Form Array. The child of this Form Array is an array of Form Groups.
  • The creation of each inner Form Group is handled to the function buildExperienceBlock(). We called this function once during the initialization phase to initialize the experienceBlocks Form Array with one experience block as a start.

3. We can easily now add a new experience block when the user clicks the add experience button as follows:

addExperience() {
 this.experienceBlocks.insert(0, this.buildExperienceBlock()); 
}

4. Lastly, we should loop through the Form Array in our template using *ngFor directive as follows:

<form (ngSubmit)="save()" [formGroup]="resumeBuilderForm">
....
 <div formArrayName="experienceBlocks" *ngFor="let experience of
  experienceBlocks.controls; let i = index">
   <div [formGroupName]="i">
     <label attr.for="{{ 'titleId' + i }}">Title</label>
     <input 
        id="{{ 'titleId' + i }}" 
        type="text"
        placeholder="Ex: Software Engineer"
        formControlName="title"/>
        ....
   </div>
  </div>
...
</form>

I hope you found this article useful!

featured_image
About the Author

Rasha Essam

Software Engineer at Andela

Thanks for subscribing!

 

More Insights

How to Scan for Android Bluetooth Low Energy Devices Successfully

The Use Case Scan for all available Android devices supporting BLE, Use any Android device with And...

15_April_2020

Shifting to Remote Onboarding of Engineers in the New Normal

With millions of tech businesses working in all-remote mode for the first time, companies are confro...

14_April_2020

While Some Regions Struggle to Work Remotely, Andela Is Ready to Help

The massive shift to remote work caused by the coronavirus has exposed the limitations of some outso...

9_April_2020

Human Factors: Managing Remote Teams in the New Normal

Technical expertise is a prized value on engineering teams. But when it comes to team leadership, su...

6_April_2020

Making the Shift to All-Remote Teams: It’s Not Just About the Tools

You’ve probably read a few articles recommending collaboration tools like instant messaging (Slack...

1_April_2020

10 Commandments for Remote Workers: Follow These to Crush the New Normal 

Fun fact: I've been a remote employee for my entire career. I've never had an office to commute...

30_March_2020

Partners

Tap into a global talent pool and hire the “right” developers in days, not months.

Developers

Accelerate your career by working with high-performing engineering teams around the world.

Hire Developers

We take great pride in matching our developers with the best partners. Tell us about your team below!

preloader_image

Thank you for your interest

A member of our team will reach out to you soon.