Getting started with Reactive Forms in Angular

Rohini Girase
Nov 1 · 2 min read

I often see people making use of NgModel with form-elements like inputs to get form data, although this approach helps you achieve your target, but there are so many things you have to do to achieve it like creating model for the input params and writing lengthy codes to play around it. If you are working on Angular 4+ projects this article is just for you. In this article I will help you understand how you can achieve the same with Reactive forms and once you implement them you will know how awesome and powerful they are.

So Let’s start…

We will start with a basic implementation of FormGroup and adding validations to the input elements which are referred as FormControls. We are going to create a simple Registration form step by step ( I am assuming you have already created an Angular project, if not just create one using cmd ng new ReactiveForms)-

Let us create the below form…

Step 1: Import ReactiveFormsModule in your app.module.ts file.

Step 2: Create a component user-form using cmd ng g -c user-form.

Step 3: It is always better to create the form structure in ts file before creating the html inputs. For our form this is how the formGroup should be created.

this.userForm = this.fb.group({
firstName: [''],
middleName: [''],
lastName:[''],
email: [''],
phone: ['']
})
}

FirstName, MiddleName, LastName, Email and Phone are the FormControls and userForm is the FormGroup.

Step 4: Let us now attach these formControls to the inputs in Html file. We will give formControlName to the inputs, so that reactive forms know these inputs.

<input type=”text” class=”form-control" formControlName=”firstName”>
<div class=”container” [formGroup]=”userForm” *ngIf=”userForm”>

This is the most important line, this tells angular that the formControls are the part of this formGroup.

Are you wondering why there is a ngIf=”userForm”, the reason is in large scale applications say due to some API response your form does not get created then it should not break our UI, for safe side it’s always good to have null check conditions.

Finally to know how the form returns the input after we submit it write a console.log to print the form value, i.e

this.userForm.value

this will return something like

Source code available on https://github.com/rohini24/ReactiveForms

That’s it 😀, Thank you for reading my first Article.

Happy coding!!!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade