Blog

  • Reactive Forms in Angular 2

    Posted by Manisha Kirodiwal | Last Updated: 28-Nov-17

    Model-based forms/ Reactive forms allow us to test our forms without having to depend on end-to-end testing.

    FormGroup and FormControl:

    Let's start with a registration form example: Now to make form a model driven form, we need to create a form model which represents the DOM structure in the component. We can use the low-level Apis for FormGroup and FormControl.

    FormGroup = A set of FormControls

    import { Component } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      ...
    })
    export class AppComponent {
    
      registerForm = new FormGroup({
        firstname: new FormControl(),
        lastname: new FormControl(),
        address: new FormGroup({
          street: new FormControl(),
          zip: new FormControl(),
          city: new FormControl()
        })
      });
    }
    

    Here we have created a component registerForm that represents FormGroup. For each field in the form, we have created a FormControl. FormGroup can be nested, as the address is a collection of form controls.

     

    Binding forms using formGroup, formGroupName, and formControlName:

     

    We will use formGroup directive to associate the model with our form. This directive takes an expression that evaluates to an instance of FormGroup.

    First import ReactiveFormModule for directive.

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@anglar/platform-browser';
    import { ReactiveFormsModule } from '@angular/forms';
    
    @NgModule({
      imports: [BrowserModule, ReactiveFormsModule],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Use formGroup to bind the model with the form template.

    ...

    Each form control obtains an applied formControlName directive so that we can register the controls in the external form:

     

    FormBuilder:

     

    FormBuilder is high-level API which we can use to make our code more pleasant. It's like a factory which creates FormGroup’s and FormControl’s. Use .group() method after import FormBuilder.

    import { FormBuilder, FormGroup } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      ...
    })
    export class AppComponent implements OnInit {
    
      registerForm: FormGroup;
    
      constructor(private formBuilder: FormBuilder) {}
    
      ngOnInit() {
        this.registerForm = this.formBuilder.group({
          firstname: '',
          lastname: '',
          address: this.formBuilder.group({
            street: '',
            zip: '',
            city: ''
          })
        });
      }
    }
    

    Forms with a single control:

     

    FormControl directive does not have to be inside a formGroup.We can add it to a single form control as follows:

    
    
    

    Here we can listen reactively for all the changes that are happening to the control.We can subscribe to valueChanges() observable property for each Form Control.

    @Component()
    export class SearchComponent implements OnInit {
    
      searchControl = new FormControl();
    
      ngOnInit() {
        this.searchControl.valueChanges.subscribe(value => {
          // do something with value here
        });
      }
    }
    

Tags: Angular