Reactive forms validation

In this article we discuss how to create forms using [formGroup] directive. We need to first import “ReactiveFormsModule” from ‘@angular/forms’ in module file “app.module”.

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


Lets create login form using validation using “ReactiveFormsModule” module.

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

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent implements OnInit  {
  name = 'Angular';
  loginForm: FormGroup;
  submitted:boolean = false;

  constructor(private formBuilder: FormBuilder) { 

  ngOnInit() {
        this.loginForm ={
            email: ['', [Validators.required,]],
            password: ['', [Validators.required, Validators.minLength(6)]]

  get v() { return this.loginForm.controls; }

  onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.loginForm.invalid) {



Below is the code for template.

 <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
                    <div class="form-group">
                        <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && }" />
                        <div *ngIf="submitted &&" class="invalid-feedback">
                            <div *ngIf="">Email is required</div>
                            <div *ngIf="">Email must be a valid email address</div>
                    <div class="form-group">
                        <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && v.password.errors }" />
                        <div *ngIf="submitted && v.password.errors" class="invalid-feedback">
                            <div *ngIf="v.password.errors.required">Password is required</div>
                            <div *ngIf="v.password.errors.minlength">Password must be at least 6 characters</div>
                    <div class="form-group">
                        <button [disabled]="loading" class="btn btn-primary">Login</button>

Below is the full embeded code.