What are reactive forms?

Reactive forms is a model-driven approach for creating forms in a reactive style(form inputs changes over time). These are built around observable streams, where form inputs and values are provided as streams of input values. Let's follow the below steps to create reactive forms,

  1. Register the reactive forms module which declares reactive-form directives in your app

    import { ReactiveFormsModule } from '@angular/forms';
    @NgModule({
    imports: [
    // other imports ...
    ReactiveFormsModule,
    ],
    })
    export class AppModule {}
  2. Create a new FormControl instance and save it in the component.

    import { Component } from '@angular/core';
    import { FormControl } from '@angular/forms';
    @Component({
    selector: 'user-profile',
    styleUrls: ['./user-profile.component.css'],
    })
    export class UserProfileComponent {
    userName = new FormControl('');
    }
  3. Register the FormControl in the template.

    <label> User name: <input type="text" [formControl]="userName"> </label>

    Finally, the component with reactive form control appears as below,

    import { Component } from '@angular/core'; import { FormControl } from '@angular/forms';
    @Component({
    selector: 'user-profile',
    styleUrls: ['./user-profile.component.css']
    template: `
    <label>
    User name:
    <input type="text" [formControl]="userName">
    </label>
    `
    })
    export class UserProfileComponent {
    userName = new FormControl('');
    }

May 14, 2022
200