Reactive Form In Angular

|
| By Webner

In Angular there are two ways to work with forms:

  • Template-driven forms:

    Template-driven forms are the default way to work with forms in Angular which is used as an internal representation of the form.

  • Reactive forms:

    Reactive forms allow us to build our own representation of a form in the component Class.

* Reactive forms are more flexible than Template-driven forms as you can keep your logic in the component class and make your templates simple.

In Reactive forms, you can use the custom validators, change the validation dynamically, dynamically add form fields

Steps to use Reactive form in our project:

Step 1: Import the ReactiveFormsModule and add in NgModule’s import array in the app.module.ts file.

 import { ReactiveFormsModule } from '@angular/forms'; //import form module

 @NgModule({
  imports: [
      ReactiveFormsModule        //Adding in NgModule's imports array 
   ],
  })

  export class AppModule { }

Step 2: Add a component using the following command in the command line

      ng generate component Component_Name

Step 3: After generating component, import form control in Component_Name.component.ts file.

   import { FormControl } from '@angular/forms';

Step 4: Create a new instance of the form control in a component class as a class property in Component_Name.component.ts file.

export class Component_Name {
  name = new FormControl(''); // create new instance of formcontrol to set its initial value
}

Step 5: Register the control into the template for association with the element in Component_Name .component.html

Example:

<label>
 EmployeeName:
  <input type="text" [formControl]="name">  //bind the form control with the element 
</label>

<label>
  Value: {{ name.value }}  //displaying  the current value using interpolation in the template
</label>

Leave a Reply

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