Welcome Guest! (App Version 3.1)

websitnero logo name

Reactive Forms

Reactive Forms in Angular

"Reactive Forms" are pretty complex to the template-driven forms as most of the validation logic is now present in the logic (.ts) file. There are certain syntaxes that you will need to follow. The benefit that comes with the burden of complexity is that -- all the validation code is "unit -testable".

Practical Example of "Reactive Forms Validation"

Please follow the mentioned steps:

  1. Create a component named 'home' and add it in the app.component.html file removing all boilerplate code there.
  2. Add the ReactiveFormsModule to the app.module.ts and also add it in the imports array in the file.
  3. Add 2 inputs for 'Name' and 'Email' for a user in the home.component.html file.
  4. Add the error messages for -- 'required', 'minlength' and 'email' in the view (.html) file. Also, add validations for them using inbuilt functions of ReactiveModule in the logic (.ts) file.
  5. Add some CSS styles in the home.component.css file to add color to the lines depicting error.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';

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

home.component.html

<div class="homeBoard">

  <form [formGroup]="someForm" (ngSubmit)="alpha()">

    <label>Enter Your Name: </label>
    <input type="text" id="firstName" class="form-control" formControlName="firstName" [ngClass]="{'red':someForm.get('firstName').touched && someForm.get('firstName').invalid}"><br/>
    <div class="invalid-feedback" *ngIf="someForm.get('firstName').touched && someForm.get('firstName').invalid">
      <div *ngIf="someForm.get('firstName').errors.required" class="error">Name is a required field!</div>
      <div *ngIf="someForm.get('firstName').errors.minlength" class="error">Minimum 3 characters are required!</div>
    </div>

    <label>Enter your Email: </label>
    <input type="text" id="email" class="form-control" formControlName="email" [ngClass]="{'red':someForm.get('email').touched && someForm.get('email').invalid}"><br/>
    <div class="invalid-feedback" *ngIf="someForm.get('email').touched && someForm.get('email').invalid">
      <div *ngIf="someForm.get('email').errors.required" class="error">Email is a required field!</div>
      <div *ngIf="someForm.get('email').errors.minlength" class="error">Minimum 5 characters are required!</div>
      <div *ngIf="someForm.get('email').errors.email" class="error">This is not a valid Email!</div>
    </div>

    <button type="submit" [disabled]="!someForm.valid">Submit</button>

  </form>

</div>

home.component.ts

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

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

  someForm: FormGroup;

  constructor() { }

  ngOnInit() {
    this.someForm = new FormGroup({
      firstName: new FormControl('', [Validators.required, Validators.minLength(3)]),
      email: new FormControl('', [Validators.required, Validators.minLength(5), Validators.email])
    });
  }

  alpha(){
    console.log(this.someForm.value);
    console.log(this.someForm.get('firstName').errors);
  }

}

home.component.css

label {display:inline-block;width:150px;margin-bottom:10px;}
.error {color:red;margin-bottom:10px;}
  1. Following will be the output:

  1. On clicking submit you will see following output in console:

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.