Home Angular Tutorials How To Use Angular Reactive Forms ?

How To Use Angular Reactive Forms ?

by aouidane.med.amine
64,324 views 20 min read

In this tutorial, we are going to see how to use the Angular Reactive forms approach to create advanced forms.

In Angular, we can use two different approaches to create forms. 

The template-driven forms and the reactive-forms.

In the template-driven form, we find all the validations and logic inside the HTML template whereas in the reactive forms we find everything inside the component (form creation, validations … ).

So, Angular Reactive forms approach is very recommended if we want to create advanced and complex forms.

Table of Contents

What is Angular Reactive Forms Approach ?

Angular reactive forms is an approach where we build the form directly in the component file.

Using this approach, we can create our form structure using formGroup, fromControl and formArray, and we use them through the formBuilder module to build the form (optional).

Unlike the template-driven forms, all the validation rules are defined in the component file when we create the form structure.

How to use Angular Reactive Forms Approach ?

To use angular reactive forms, we need first to import the ReactiveFormsModule in your component module (exp : appModule ).

Then, we can create the form structure using the formGroup , the formControl and the formArray depending on your needs. 

Finally, you create the HTML template and make the same form structure that was created in the component file.

How to Import ReactiveFormsModule ?

The first thing to do, when we use the reactive forms approach to build out forms, is the import of the ReactiveFormsModule in the component module. 

It’s recommended to import the ReactiveFormsModule in the shared module if we have one.

Otherwise we try to import it in a root module, which prevents us from importing the same module multiple times in the project.

				
					import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {ReactiveFormsModule} from "@angular/forms";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

				
			

Create The Form Model

In the reactive forms approach, we manually create the form structure in the component.

To do that, we need to import the @angular/forms that provides multiple methods to create the form structure.

Generally, an angular Form must contain at least one element.

If we have only one element, we can use the formControl method that represents a single form element.

Otherwise, we can use the FormGroup method that contains multiple formControl.

In some cases, when we want to add and remove formControls and formGroups dynamically, we need to use the formArray method. 

the formArray represents an array of fromControl or formGroup, that means, w can push, remove and access to any formArray element based on the element index like any regular array.

				
					import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  title = 'XperTuto.com : Angular Reactive forms Approach';

  userForm: FormGroup = new FormGroup({});

  constructor(private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.initializeForm();
  }

  initializeForm(): void {
    this.userForm = this.formBuilder.group({
      pseudo: new FormControl('XperTuto', Validators.required),
      name: new FormControl('Aouidane', Validators.required),
      age: new FormControl(''),
      email: new FormControl(''),
    });
  }
}

				
			

Build The HTML Template

Till now, we have the model structure of our form that was created in the component file. Now we need to create the HTML template.

In the template, we will start by creating a regular HTML form, and we will see how to bind it in the next step.

Note that im using the Angular Material in my example to style the HTML form, it’s optional , so you can use the regular HTML from elements with no problems.

				
					<form>

  <mat-card>
    <mat-form-field appearance="fill">
      <mat-label>Pseudo*</mat-label>
      <input matInput type="text" placeholder="Pseudo">
    </mat-form-field>
    
    <mat-form-field appearance="fill">
      <mat-label>Name*</mat-label>
      <input matInput type="text"  placeholder="Name">
    </mat-form-field>
    
    <mat-form-field appearance="fill">
      <mat-label>Age</mat-label>
      <input matInput type="text"  placeholder="Age">
    </mat-form-field>
    
    <mat-form-field appearance="fill">
      <mat-label>Email</mat-label>
      <input matInput type="text"  placeholder="Email">
    </mat-form-field>
  </mat-card>
  
</form>

				
			

How To Bind The Template To The Model ?

The regular HTML form in angular means nothing if there is no binding between the HTML form and the model.

  • To bind the formGroup :  we need to use the [formGroup] directive and assign it to the model that was created in the component.
  • To bind the formControl : we need to add the formControlName directive and assign it to the control name in the model.
  • To bind the nested formGroup: we need to add the formGroupName directive and assign it to the nested formGroup name in the model
				
					<form [formGroup]="userForm"></form>

<input matInput type="text" formControlName="pseudo" placeholder="Pseudo">
				
			

Submit The Form

To submit the form and get the form data in the component, we can use two methods : 

The first method is based on event binding, we just add the ngSubmit directive and assign it to the function in the component.

In the function, we can access the form data using the object in the parameter.

The second method is to use a simple button that calls a function in the component. 

In this function, we can access the form data using the local formGroup model.

check the full Code example and the result :

				
					<!--app.component.html-->

<form [formGroup]="userForm" (ngSubmit)="adduser()">

  <mat-card>
    <mat-form-field appearance="fill">
      <mat-label>Pseudo*</mat-label>
      <input matInput type="text" formControlName="pseudo" placeholder="Pseudo">
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Name*</mat-label>
      <input matInput type="text" formControlName="name" placeholder="Name">
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Age</mat-label>
      <input matInput type="text" formControlName="age" placeholder="Age">
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Email</mat-label>
      <input matInput type="text" formControlName="email" placeholder="Email">
    </mat-form-field>
  </mat-card>

  <mat-card-actions>
    <br>
    <button type="submit" mat-raised-button color="primary">Submit</button><br><br>
  </mat-card-actions>

</form>

				
			
				
					/*app.component.ts*/

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  title = 'XperTuto.com : Angular Reactive forms Approach';

  userForm: FormGroup = new FormGroup({});

  constructor(private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.initializeForm();
  }

  initializeForm(): void {
    this.userForm = this.formBuilder.group({
      pseudo: new FormControl('XperTuto', Validators.required),
      name: new FormControl('Aouidane', Validators.required),
      age: new FormControl(''),
      email: new FormControl(''),
    });
  }

  adduser() {
    // call API
    console.log(this.userForm.getRawValue());
  }
}

				
			
angular reactive forms example

References

Clone The Project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/angular_reactive_forms.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Forms :

Recapitulation

In this tutorial, we have seen how to use the angular reactive forms approach to build advanced forms. Also, we have seen different methods and directives provided by angular when we use this approach, and that may help us to decide what approach to use before building a new Angular form.

I hope you enjoy reading this Tutorial.

You may also like