Skip to main content

Importance of Reactive Forms in Angular

 Reactive Forms

The Form object will be programmatically created by angular and the entire FORM object will be synchronized with DOM.

Before sending data any manipulation needs to be done then prefer to use the Reactive form.

  • FormGroup: => Manages multiple FormControls as a group, ideal for grouping related                                      controls.

  • FormControl => Tracks the value and validation status of a single form element.

  • FormBuilder => is a service provided by Angular to simplify the creation of FormGroup and                                 FormControl objects.

  • FormArray => Manages an array of FormControls, useful for dynamic lists of inputs.

  • ControlValueAccessor => Creates a bridge between a form control and the Dom element









  • Ex.html:

    <div class="container">
      <form [formGroup]="loginForm">
        Name: <input type="text" class="form-control" formControlName="name"/>
        Password: <input type="text" class="form-control" formControlName="password"/>

        <div class="text-danger" *ngIf="loginForm.controls['password'].touched">
          <span *ngIf="loginForm.controls['password'].errors?.['required']">This is Required</span>
          <span *ngIf="loginForm.controls['password'].errors?.['minlength']">3 Charecter Required</span>
        </div>

        <button class="btn btn-success" [disabled]="loginForm.invalid" (click)="onSave()">Submit</button>
      </form>
    </div>

    Value is: {{objs|json}}

    Ex.ts:

    //imports: [ReactiveFormsModule,JsonPipe,CommonModule],
    export class PraticeComponent  {
      objs: any;
     
      loginForm:FormGroup = new FormGroup({
        name: new FormControl(''),
        password: new FormControl('',[Validators.required,Validators.minLength(3)])
      });

      onSave(){
        this.objs = this.loginForm.value
      }
    }


    //imports: [ReactiveFormsModule,JsonPipe,CommonModule],

    export class PraticeComponent  {

     //Form Builder Approach

      objs: any;
      loginForm!: FormGroup;

      constructor(private fb: FormBuilder) {
      this.loginForm=this.fb.group({
           name: new FormControl(''),
           password: new FormControl('',[Validators.required,Validators.minLength(3)])
         });
        }
      onSave(){
        this.objs = this.loginForm.value
      }
    }

    More details GithubRepo

    Comments

    © 2020 The JavaDS Hub

    Designed by Open Themes & Nahuatl.mx.