Angular Reactive Forms With Validation Example

First, you need to import the required modules in your component:

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

Then, you can create the form using the FormBuilder service:

  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {

  createForm() {
    this.myForm ={
      name: ['', Validators.required],
      email: ['', [Validators.required,]],
      message: ['', Validators.required]

In this example, the myForm property holds the reactive form instance. The createForm method uses the FormBuilder service to create the form and define its fields with initial values and validators. The name field is required, the email field is required and must be a valid email address, and the message field is required.

Now, you can use this form in your template:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <label for="name">Name:</label>
  <input type="text" id="name" formControlName="name">
  <div *ngIf="myForm.get('name').invalid && (myForm.get('name').dirty || myForm.get('name').touched)">
    <div *ngIf="myForm.get('name').errors.required">Name is required.</div>

  <label for="email">Email:</label>
  <input type="email" id="email" formControlName="email">
  <div *ngIf="myForm.get('email').invalid && (myForm.get('email').dirty || myForm.get('email').touched)">
    <div *ngIf="myForm.get('email').errors.required">Email is required.</div>
    <div *ngIf="myForm.get('email')">Invalid email format.</div>

  <label for="message">Message:</label>
  <textarea id="message" formControlName="message"></textarea>
  <div *ngIf="myForm.get('message').invalid && (myForm.get('message').dirty || myForm.get('message').touched)">
    <div *ngIf="myForm.get('message').errors.required">Message is required.</div>

  <button type="submit" [disabled]="myForm.invalid">Submit</button>

In this example, the formGroup directive binds the myForm instance to the form element. The formControlName directive binds each form control to the corresponding field in the myForm instance. The *ngIf directives display error messages for each field if it's invalid and has been touched or is dirty.

Finally, you can handle the form submission in your component:

onSubmit() {
  // Do something with the form data

This is a basic example, but you can add more validation rules and custom validators as needed.

Similar Articles