simple example of angular 4 validations | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

To upgrade our form into an Angular form that can perform validation, we have to createFormControl andFormGroupobjects. A FormControl object represents a form control in a form. With it, we can track the value and validation status of an individual form control. AFormGroup object tracks the value and validity state of a group of FormControl objects.


Step 1: Create new angular cli project.

Step2: Create new controller.

ng g c validationexample –flat


Step 3: Add following code into validationexample.component.html

  validationexample works!
<form [formGroup]="form" (ngSubmit)="login()">
  <div class= "form-group">
<label for="username">User Name</label>
<input type="text" formControlName="username" class="form-control" />
<div *ngIf="form.controls.username.touched && !form.controls.username.valid" class="alert alert-danger">Username is required
    <div class= "form-group">
  <label for="password">Password</label>
  <input type="text" formControlName="password" class="form-control" />
  <div *ngIf="form.controls.password.touched && !form.controls.password.valid" class="alert alert-danger">Password is required</div>
    <input class="btn btn-primary" [disabled]="form.invalid" type="submit" value="Submit" />



Step4: Add following code into validation.component.ts

import { Component, OnInit } from '@angular/core';

import { FormGroup , FormControl ,Validators, NgForm} from '@angular/forms';

  selector: 'app-validationexample',
  templateUrl: './validationexample.component.html',
  styleUrls: ['./validationexample.component.css']
export class ValidationexampleComponent  {
// create formgroup object and add formcontrol to perform validations
  form = new FormGroup({
         username: new FormControl('', Validators.required),
         password: new FormControl('', Validators.required)

Step 5: Pass reference of newly created component(validationexample) to app.component.html

<h2>App Component</h2>

Step 6: Run application

ng serve –open