How to use Reactive Forms in Angular?w

All the form elements, user interactions and validations are handled in the component class.

We will make sue of angular built in formGroup and formControl

Using reactive forms, we can control better data binding.

Exclusive define custom regular expression patterns of error handling.

We will need to import ReactiveFormsModule in our app module.

Very flexible and allows users to define, develop complex requirements of forms.

More logic in the component class and less in HTML markup itself.

How to use Reactive Form:

  • Step 1: import and add in the ReactiveFormsModule in the app.module.ts
  • Step 2: create the form in app.component.html
  • FormGroup dash; we need to use the directive FormGroup for the entire form and give it a name
  • formControlName dash; every form filed should have a
  • formControlName attribute
  • Step 3: in the component class dash; import the required modules
import {Component, OnInit} from

import {FormBuilder, FormGroup, FormControl, NgForm, Validatiors} from ‘@angular/forms’;
  • Step 4: inject the FormBuilder in the constructor

constructor (private formBuilder: FormBuilder)

  • Step 5: Create the form instance
this.loginForm ={ 

username:new FormControl(), 

password: new FormControl()