Tuesday, 30 June 2020

Reactive Form with validation

Write the following code under .html file

div class="container">
    <h2 style="color: crimson;">Product Registration</h2>
    <form [formGroup]="frmRegister">
        <legend>Basic Details</legend>
        <div class="form-group">
            <label for="">Product Name</label>
            <input type="text" formControlName="Name" class="form-control">
            <span class="alert alert-danger" *ngIf="Name.touched && Name.invalid">
                <div *ngIf="Name.errors.required">Name is Required</div>
                <div *ngIf="Name.errors.minlength">Name should be of {{Name.errors.minlength.requiredLength}} Characters</div>
            </span>
        </div>
        <div class="form-group">
            <label for="">Price</label>
           &#8377;<input type="text" formControlName="Price" class="form-control">
        </div>
        <div formGroupName="frmDetails">
            <legend>Stock Details</legend>
        <div class="form-group">
            <label for="city">Shipped To</label>
            <select name="City" id="city" formControlName="City" class="form-control">
                <option value="">Select City</option>
                <option >Pune</option>
                <option >Delhi</option>
                <option >Mumbai</option>
            </select>
        </div>
        <div class="form-group">
            <label for="IsInStock">IsInStock</label>&nbsp; &nbsp;
            <input type="checkbox" id="IsInStock" formControlName="IsInStock">Yes
        </div>
        <div class="form-group">
            <button [disabled]="!frmRegister.valid" class="btn btn-primary" type="submit" (click)="updateDetails()">Submit</button>
        </div>
        </div>
    </form>
    <br>
    Name: {{frmRegister.value.Name}}
    <br>
    Price: {{frmRegister.value.Price}}
    <br>
    City: {{frmRegister.value.frmDetails.City}}
    <br>
    IsInStock : {{frmRegister.value.frmDetails.IsInStock}}
</div>

Write the following code under .ts file

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

@Component({
  selector: 'app-nestedform',
  templateUrl: './nestedform.component.html',
  styleUrls: ['./nestedform.component.css']
})
export class NestedformComponent  {

public frmRegister = new FormGroup({
Name: new FormControl('', [Validators.required, Validators.minLength(3)]),
Price: new FormControl('', Validators.required),
frmDetails: new FormGroup({
City : new FormControl(''),
IsInStock : new FormControl('')
}),
});

updateDetails() {
  console.log(this.frmRegister.value);
}

get Name(){
  return this.frmRegister.get('Name');
}

}

OutPut:




Posted By: pankaj_bhakre

No comments:

Post a Comment