How to add validation in angular component dynamically

In this post, I will show you how to add validation to angular component dynamically.
Sometimes we need to show the control based on the user selection. For this post I have created a simple project in which there are two controls one is textbox and another is checkbox. When the user click on the checkbox we will add the required validation to textbox


Let’s start the tutorial.

Create an application using angular-cli

ng new dynamic-validation

Open app.component.htm and add following markup

<h2>Add validation</h2>

<div class="row">
	<form [formGroup]="form">
		<div class="form-group">
			<label for="email">Email</label>
			<input type="text" class="form-control"  id="email" formControlName="email">
			<div class="alert alert-danger"
				*ngIf=" form.get('email').touched && form.get('email').errors && form.get('email').errors.required">
				Email is required

		<div class="form-group">
			<div class="form-check">
				<input class="form-check-input" formControlName="isRequired" (change)="addValidation()" type="checkbox" id="gridCheck">
				<label class="form-check-label" for="gridCheck">
      Email Is Required

		<input type="button" class="btn btn-success" value="Submit" [disabled]="!form.valid">

After that open app.component.ts file and add following code

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

  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
export class AppComponent {
  form: FormGroup;
  constructor() {
  ngOnInit() {}
  addValidation() {
    const emailCtrl = this.form.get("email");
    const val = this.form.get("isRequired").value;
    if (val === true) {
    } else {
  createForm() {
    this.form = new FormGroup({
      email: new FormControl(),
      isRequired: new FormControl(false)


Next Post Previous Post
No Comment
Add Comment
comment url