Address
Darbhanga, Bihar 846004

 

Reactive Forms in Angular

Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time. Each change to the form state returns a new state, which maintains the integrity of the model between changes. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.

Example:

form.component.htm

<form [formGroup]="stuObj">
  <label class="form-label">First name</label>
  <input
    type="text"
    name="fName"
    class="form-control"
    formControlName="fName"
  />
  <div class="text-danger">
    @if ((stuObj.controls['fName'].touched || stuObj.controls['fName'].dirty )&&
    stuObj.controls['fName'].errors?.['required']) {
    <span> This is Required</span>
    } @else if(stuObj.controls['fName'].touched ||
    stuObj.controls['fName'].dirty &&
    stuObj.controls['fName'].errors?.['minlength']) {
    <span> Min char 3 required</span>
    } ……
  </div>
  <button
    class="btn btn-primary mx-2"
    type="button"
    [disabled]="stuObj"
    (click)="onSubmit()"
  >
    Submit
  </button>
</form>

form.component.ts

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

imports: [ReactiveFormsModule],

  stuObj = new FormGroup({
    fName: new FormControl('', [Validators.required, Validators.minLength(3)]),
     ……..
  })
formValue: any;
onSubmit() {
  this.formValue = this.stuObj.value;
}

Leave a Reply

Your email address will not be published. Required fields are marked *