Overview of Reactive Approach In Angular

In this tutorial, I am talking about two approaches that Angular offers - Template Driven and Data Driven (Reactive Approach).

Template Driven approach is the traditional approach which we are using since Angular 1.x. Even in Angular two way binding, we use the same approach.

Data Driven or Reactive Forms Module is different than the template driven approach. In the reactive approach, you create a tree of Angular form objects using form builder in the component class (i.e. your .ts file ) and bind them to native form control elements in the component template (i.e. your .html file).  It is more or less the same as what we do in ASP.NET MVC (Model).

One advantage of directly working with form control objects is that the value and validity updates are always synchronous and under your control. You won't encounter the timing issues that sometimes plague a template-driven form, and reactive forms are way easier to unit test. (Source Courtesy Angular.io). 

Which one is better - Template Driven or Reactive?? 

Neither Reactive nor Template Driven are better over each other. They both are different approaches, so you can use whichever suits your needs the most. You can even use both in the same application.

So, in this tutorial, I am talking about the following terms.

  • Reactiveform Module
  • Form Control
  • FormGroup
  • FromBuilder
  • Validators
  • And more..

Now enough of introduction and theory, let’s dive into the code. The environment used by me to create this demo is Visual Studio Code as IDE, and Angular-Cli 1.1.3.

In order to use Reactive forms module, we need to import it from @angular/forms, as shown below, and declare it in imports array of app.module.ts file.

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     NgModule  
  6. } from '@angular/core';  
  7. import {  
  8.     ReactiveFormsModule  
  9. } from "@angular/forms";  
  10. import {  
  11.     HttpModule  
  12. } from "@angular/http";  
  13. import {  
  14.     AppComponent  
  15. } from './app.component';  
  16. @NgModule({  
  17.     declarations: [  
  18.         AppComponent  
  19.     ],  
  20.     imports: [  
  21.         BrowserModule,  
  22.         ReactiveFormsModule,  
  23.         HttpModule  
  24.     ],  
  25.     providers: [],  
  26.     bootstrap: [AppComponent]  
  27. })  
  28. export class AppModule {}  

Now, we will generate a new component using angular-cli.

ng g c products

products.component.html

  1. <div class="container">  
  2.     <div class="row">  
  3.         <div *ngFor="let item of allProduct" class="col-sm-6 col-md-4">  
  4.             <div class="thumbnail"> <img height="250" src="{{item.pimg}}" alt="...">  
  5.                 <div class="caption">  
  6.                     <h3>{{item.pname}}</h3>  
  7.                     <p>{{item.pprice | currency:'INR':true }}</p>  
  8.                     <p><a class="btn btn-primary" role="button">{{item.soh}}</a> <a class="btn btn-default" role="button">Button</a></p>  
  9.                 </div>  
  10.             </div>  
  11.         </div>  
  12.     </div>  
  13. </div>  

products.component.ts

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-products',  
  7.     templateUrl: './products.component.html',  
  8.     styleUrls: ['./products.component.css']  
  9. })  
  10. export class ProductsComponent implements OnInit {  
  11.     allProduct: any = [{  
  12.         "p_id": 1,  
  13.         "pname""omega",  
  14.         "pprice": 100000,  
  15.         "pimg""http://cdn2.jomashop.com/media/catalog/product/o/m/omega-seamaster-planet-ocean-black-dial-men_s-watch-232.30.42.21.01.001_1.jpg",  
  16.         "soh": 5  
  17.     }, {  
  18.         "p_id": 2,  
  19.         "pname""timex",  
  20.         "pprice": 2000,  
  21.         "pimg""http://ecx.images-amazon.com/images/I/51Ezfl22mYL._AC_UL260_SR200,260_.jpg",  
  22.         "soh": 10  
  23.     }, {  
  24.         "p_id": 3,  
  25.         "pname""titan",  
  26.         "pprice": 12000,  
  27.         "pimg""http://ecx.images-amazon.com/images/I/51fnWFY3s3L._AC_UL260_SR200,260_.jpg",  
  28.         "soh": 15  
  29.     }, {  
  30.         "p_id": 4,  
  31.         "pname""fossil",  
  32.         "pprice": 18000,  
  33.         "pimg""http://i.ebayimg.com/00/s/NjAwWDYwMA==/z/ZN8AAOSwd4tT5KNF/$_32.JPG",  
  34.         "soh": 8  
  35.     }, {  
  36.         "p_id": 5,  
  37.         "pname""rolex",  
  38.         "pprice": 125000,  
  39.         "pimg""http://dvciknd2kslsk.cloudfront.net/images/watchfinderimages/Watch/Rolex/GMT-Master-II/76399-2005568029.jpg",  
  40.         "soh": 3  
  41.     }, {  
  42.         "p_id": 6,  
  43.         "pname""fast track",  
  44.         "pprice": 3000,  
  45.         "pimg""http://www.shadestation.co.uk/media/product_images/Uboat-Watches-Titaniumd.gif",  
  46.         "soh": 10  
  47.     }, {  
  48.         "p_id": 7,  
  49.         "pname""citizen",  
  50.         "pprice": 15000,  
  51.         "pimg""https://static2.ethoswatches.com/media/catalog/product/cache/1/small_image/498x750/9df78eab33525d08d6e5fb8d27136e95/c/i/citizen-casual-an8070-53a.jpg",  
  52.         "soh": 5  
  53.     }, {  
  54.         "p_id": 8,  
  55.         "pname""guess",  
  56.         "pprice": 15800,  
  57.         "pimg""https://static2.ethoswatches.com/media/catalog/product/cache/1/small_image/498x750/9df78eab33525d08d6e5fb8d27136e95/a/n/an8070-53a.jpg",  
  58.         "soh": 10  
  59.     }];  
  60.     constructor() {}  
  61.     ngOnInit() {}  

So far, we have created one component and displayed the products from the array. Output should be something like below.

Reactive

Now, as the product display is done, we want to create a product addition form using reactive form approach. So, first of all, in our component, we need to import the following packages to our TypeScript file, i.e., products.component.ts 

  1. import { FormGroup,FormBuilder,Validators,FormControl } from '@angular/forms';   

Then, create an object of FormGroup and name it as myForm.

  1. export class ProductsComponent implements OnInit {  
  2.     myForm: FormGroup;  
  3.     constructor(private formbuilder: FormBuilder) {}  
  4. }   

Now, in ngOnInit method, create the instance of myForm as shown below. Also, define the rule for validations, Here, I am using both validations, inbuilt validations as well as custom validations. 

  1. ngOnInit() {  
  2.     this.myForm = this.formbuilder.group({  
  3.         'p_id': ['', Validators.required],  
  4.         'pname': ['', [Validators.required, this.exampleValidator]],  
  5.         'pprice': ['', [Validators.required, Validators.min(0)]],  
  6.         'pimg': ['', Validators.required],  
  7.         'soh': ['', [Validators.required, Validators.max(10)]]  
  8.     });  
  9. }  
  10. exampleValidator(control: FormControl): {  
  11.     [s: string]: boolean  
  12. } {  
  13.     if (control.value === "Example") {  
  14.         return {  
  15.             example: true  
  16.         };  
  17.     }  
  18.     return null;  
  19. }   

Here, on price column, I have applied two validations - one is required and the other one's minimum value must be positive. And in pname column, I have shown the demo for custom validation named as examplevalidator, in which I will throw the error if the name of product = “Example”. In this way, we can define in-built as well as custom validators in Angular. 

Entire  products.component.ts is as shown below. 

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     FormGroup,  
  7.     FormBuilder,  
  8.     Validators,  
  9.     FormControl  
  10. } from '@angular/forms';  
  11. @Component({  
  12.     selector: 'app-products',  
  13.     templateUrl: './products.component.html',  
  14.     styleUrls: ['./products.component.css']  
  15. })  
  16. export class ProductsComponent implements OnInit {  
  17.     myForm: FormGroup;  
  18.     constructor(private formbuilder: FormBuilder) {}  
  19.     onSubmit() {  
  20.         this.allProduct.push(this.myForm.value);  
  21.     }  
  22.     ngOnInit() {  
  23.         this.myForm = this.formbuilder.group({  
  24.             'p_id': ['', Validators.required],  
  25.             'pname': ['', [Validators.required, this.exampleValidator]],  
  26.             'pprice': ['', [Validators.required, Validators.min(0)]],  
  27.             'pimg': ['', Validators.required],  
  28.             'soh': ['', [Validators.required, Validators.max(10)]]  
  29.         });  
  30.     }  
  31.     exampleValidator(control: FormControl): {  
  32.         [s: string]: boolean  
  33.     } {  
  34.         if (control.value === "Example") {  
  35.             return {  
  36.                 example: true  
  37.             };  
  38.         }  
  39.         return null;  
  40.     }  
  41. }   

Here is the code for products.component.html 

  1. <div class="container">  
  2.     <h1>Add Product Demo</h1>  
  3.     <form [formGroup]="myForm" (ngSubmit)="onSubmit()">  
  4.         <div class="form-group"> <label for="Id">p_id</label> <input formControlName="p_id" type="number" id="p_id" class="form-control"> </div>  
  5.         <div class="alert alert-danger" *ngIf="myForm.get('p_id').hasError('required') && myForm.get('p_id').touched"> p_id is required </div>  
  6.         <div class="form-group"> <label for="pname">pname</label> <input formControlName="pname" type="text" id="pname" class="form-control"> </div>  
  7.         <div class="alert alert-danger" *ngIf="(myForm.get('pname').hasError('required') || myForm.get('pname').invalid ) && myForm.get('pname').touched "> product name is required and it shouldn't be Example </div>  
  8.         <div class="form-group"> <label for="pprice">pprice</label> <input formControlName="pprice" type="text" id="pprice" class="form-control"> </div>  
  9.         <div class="alert alert-danger" *ngIf="(myForm.get('pprice').hasError('required') || myForm.get('pprice').invalid) && myForm.get('pprice').touched"> pprice is required and must be positive value </div>  
  10.         <div class="form-group"> <label for="pimg">pimg</label> <input formControlName="pimg" type="text" id="pimg" class="form-control"> </div>  
  11.         <div class="alert alert-danger" *ngIf="myForm.get('pimg').hasError('required') && myForm.get('pimg').touched"> pimg is required </div>  
  12.         <div class="form-group"> <label for="soh">soh</label> <input formControlName="soh" type="text" id="soh" class="form-control"> </div>  
  13.         <div class="alert alert-danger" *ngIf="(myForm.get('soh').hasError('required') || myForm.get('soh').invalid) && myForm.get('soh').touched"> soh is required and maximum soh would be 10 </div> <button type="submit" [disabled]="!myForm.valid" class="btn btn-primary">Add Product</button> </form>  
  14. </div>   

In this products.component.html page, the most important thing is the name of the form.

[formGroup]="myForm" 

Which should be same as the name of myForm:FormGroup. 

formControlName="pname” attribute in input tag will bind it to the property of formbuilder group. Remember, we created it in our TypeScript.