View video tutorial

ANGULAR Reactive Form

ANGULAR

Reactive forms validation is a model-driven approach in Angular that uses validator functions, FormControl, FormGroup, etc.

Angular Reactive Form Example


➔ This example shows how reactive form validation works in Angular.

Create a project by ng new reactive-form-validation command.
ng new reactive-form-validation

app.module.ts file

Copy this file content to the target file.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import{FormsModule} from '@angular/forms'

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

Copy the code and try it out practically in your learning environment.


Model product.ts file

Copy this file content to the target file.

Example
export class Product {
    id?: number;
    name?: string;
    stock?: number;
    price?: number;
    images?: string;
    constructor(id?: number, name?: string, stock?: number, price?: number, images?: string) {
        this.id = id;
        this.name = name;
        this.stock = stock;
        this.price = price;
        this.images = images;
    }
}
                            

Copy the code and try it out practically in your learning environment.


app.component.ts file

Copy this file content to the target file.

Example
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Product } from './product';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    this.porducts = this.getProducts();
  }
  title = 'fromvalidation';


  getProducts(): Product[] {
    return [
      new Product(101, "Item1", 5, 50, "assets/desktop.jpg"),
      new Product(102, "Item2", 10, 100, "assets/laptop.jpg")
    ];
  }

  porducts: Product[];


  product: Product = new Product();
  product2: Product = new Product();
  setProduct(p: Product) {
    this.product = new Product(p.id, p.name, p.stock, p.price, p.images);
  }

  msg?: string;
  submit(form: any, ev: any) {
    if (ev.submitter.name == "save") {

      let found = this.porducts.find(element => element.id == form.value.id);
      if (found == null && form.value.id > 0) {
        if (form.valid) {
          var id = form.value.id;
          var name = form.value.name;
          var stock = form.value.stock;
          var price = form.value.price;
          var images = form.value.images;
          this.porducts.push(new Product(id, name, stock, price, images));

          this.msg = "Item added";
        } else {
          this.msg = "Input are not valid";
        }

      } else {
        this.msg = "Item empty or already exist";
      }

    } else if (ev.submitter.name == "delete") {
      for (let i = 0; i < this.porducts.length; i++) {
        if (form.value.id == this.porducts[i].id) {
          this.porducts.splice(i, 1);
          this.msg = "Item Deleted";
        } else {
          this.msg = "Item not Deleted";
        }
      }

    } else if (ev.submitter.name == "update") {
      for (let i = 0; i < this.porducts.length; i++) {
        if (form.value.id == this.porducts[i].id) {
          this.porducts[i].name = form.value.name;
          this.porducts[i].stock = form.value.stock;
          this.porducts[i].price = form.value.price;
          this.porducts[i].images = form.value.images;
          this.msg = "Item Update";
        }
      }
    } else {
      this.msg = "Item not Update";
    }

  }
  resetting(form: NgForm) {
    form.reset();
  }
}

Copy the code and try it out practically in your learning environment.


Note: put the images in assets folder.


HTML app.component.html File

Copy this file content to the target file.

Example
<div class="container">
  <div class="row">
    <div class="col-4">
      <p>Add Item</p>
      <h3 class="p-2 bg-white">{{ msg }}</h3>
      <form #contactForm="ngForm" (ngSubmit)="submit(contactForm, $event)">

        <div class="form-group">
          <label for="id">ID</label>
          <input type="text" class="form-control" id="id" name="id" #id1="ngModel" [(ngModel)]="product.id" required
            minlength="3" maxlength="6" pattern="^[0-9]+$">
          <div class="alert alert-danger" *ngIf="id1.touched && !id1.valid">
            <div *ngIf="id1.errors && id1.errors['required']">ID is required.</div>
            <div *ngIf="id1.errors && id1.errors['minlength']">ID is minimum {{ id1.errors &&
              id1.errors['minlength'].requiredLength }} numbers.</div>
            <div *ngIf="id1.errors && id1.errors['maxlength']">ID is maximum 6 numbers.</div>
            <div *ngIf="id1.errors && id1.errors['pattern']">ID is Numbers only.</div>
          </div>
        </div>



        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" id="name" name="name" #name1="ngModel" [(ngModel)]="product.name"
            required minlength="3" maxlength="20" pattern="^[A-Za-z0-9]+[ A-Za-z0-9]+$">
          <div class="alert alert-danger" *ngIf="name1.touched && !name1.valid">
            <div *ngIf="name1.errors && name1.errors['required']">Name is required.</div>
            <div *ngIf="name1.errors && name1.errors['minlength']">Name is minimum {{ name1.errors &&
              name1.errors['minlength'].requiredLength }} character.</div>
            <div *ngIf="name1.errors && name1.errors['maxlength']">Name is maximum 20 character.</div>
            <div *ngIf="name1.errors && name1.errors['pattern']">Name is characters and numbers only.</div>
          </div>
        </div>

        <div class="form-group">
          <label for="stock">Stock</label>
          <input type="text" class="form-control" id="stock" name="stock" #stock1="ngModel" [(ngModel)]="product.stock"
            required pattern="^[0-9]{1,5}$">
          <div class="alert alert-danger" *ngIf="stock1.touched && !stock1.valid">
            <div *ngIf="stock1.errors && stock1.errors['required']">Stock is required.</div>
            <div *ngIf="stock1.errors && stock1.errors['pattern']">Stock is number 3 to 5 digits.</div>
          </div>
        </div>

        <div class="form-group">
          <label for="price">Price</label>
          <input type="text" class="form-control" id="price" name="price" #price1="ngModel" [(ngModel)]="product.price"
            required minlength="1" maxlength="8" pattern="^[0-9.]+$">
          <div class="alert alert-danger" *ngIf="price1.touched && !price1.valid">
            <div *ngIf="price1.errors && price1.errors['required']">Price is required.</div>
            <div *ngIf="price1.errors && price1.errors['minlength']">Price is minimum {{ price1.errors &&
              price1.errors['minlength'].requiredLength }} digits.</div>
            <div *ngIf="price1.errors && price1.errors['maxlength']">Price is maximum 8 digits.</div>
            <div *ngIf="price1.errors && price1.errors['pattern']">Price is digits only.</div>
          </div>
        </div>

        <div class="form-group">
          <label for="images">Images URL</label>
          <input type="text" class="form-control" id="images" name="images" #images1="ngModel"
            [(ngModel)]="product.images" required minlength="1" maxlength="20" pattern="^[A-Za-z0-9 . /]+$">
          <div class="alert alert-danger" *ngIf="images1.touched && !images1.valid">
            <div *ngIf="images1.errors && images1.errors['required']">Images URL is required.</div>
            <div *ngIf="images1.errors && images1.errors['minlength']">Images URL is minimum {{ images1.errors &&
              images1.errors['minlength'].requiredLength }} character.</div>
            <div *ngIf="images1.errors && images1.errors['maxlength']">Images URL is maximum 20 character.</div>
            <div *ngIf="images1.errors && images1.errors['pattern']">Images URL is characters . / only.</div>
          </div>
        </div>

        <!-- <button class="btn btn-primary p-2 m-3" type="submit" [class.disabled]="!contactForm.valid">Submit</button> -->
        <button class="btn btn-primary p-2 m-3" type="submit" name="save">Save</button>
        <button class="btn btn-primary p-2 m-3" type="submit" name="delete">Delete</button>
        <button class="btn btn-primary p-2 m-3" type="submit" name="update">Update</button>
        <button type="button" (click)="resetting(contactForm)"
          class="btn btn-warning float-right p-2 m-3">Reset</button>
      </form>

    </div>
    <div class="col-1">

    </div>
    <div class="col-6">
      <table class="table">
        <thead>
          <tr>
            <th scope="col">Id</th>
            <th scope="col">Name</th>
            <th scope="col">Stock</th>
            <th scope="col">Price</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let p of porducts" (click)="setProduct(p)" data-bs-toggle="modal" data-bs-target="#exampleModal">
            <th scope="row">{{p.id}}</th>
            <td>{{p.name}}</td>
            <td>{{p.stock}}</td>
            <td>{{p.price}}</td>
            <td>{{p.images}}</td>
            <td><img src="{{p.images}}" height="60px" width="60px" /></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>



<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"><img [src]="product.images" height="200px" width="200px" /></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <ul class="list-group list-group-flush">
          <li class="list-group-item">Name: {{product.name}}</li>
          <li class="list-group-item">Id: {{product.id}}</li>
          <li class="list-group-item">Quantiy: {{product.stock}}</li>
          <li class="list-group-item">Price: {{product.price}}</li>
        </ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
        <!-- <button type="button" class="btn btn-primary">Save changes</button> -->
      </div>
    </div>
  </div>
</div>

Copy the code and try it out practically in your learning environment.


HTML index.html File

Copy this file content to the target file.

Example
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Formvalidation</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Copy the code and try it out practically in your learning environment.


Output

Run project by ng serve in command line (from inside project directory).

Angular form submit with template example

program output