Angular Reactive Forms

In the previous article you’ve seen Template Driven Forms and it’s working. TDFs were easy-to-use forms. We’ve to write a bulk of code in an HTML file and less code in a TypeScript file. But in the case of Reactive Forms, the bulk of code and logic shifts into component classes. No two-way binding is applicable in Reactive Forms.

What are Reactive Forms in Angular?

Angular provides several methods to control the form control value from the component class. Reactive forms are most suitable for complicated forms and we can also include custom and dynamic validation.

How to Create Angular Reactive Forms?

Let’s make a simple registration form to understand reactive forms in angular.

Before going into the HTML file and creating a form, the first step is to import ReactiveFormsModule in app.module.ts and also add it to the imports array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from "@angular/forms";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Now let’s quickly move into the component class file and import some classes.

  • FormControl: It is a class that gives access to all the input fields of the form.
  • FormGroup: It is a collection of every FormControls and contains all the valuable information of the form.

And now we’re ready to write code to create a Reactive Form using the two classes mentioned above.

import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  title = 'my-app';
  formvalue:any

  myform=new FormGroup({
    name:new FormControl(''),
    phone:new FormControl(''),
    email: new FormControl(''),
    address: new FormControl('')
  })

  clicked(value:any) {
    this.formvalue=value;
  }
}
  • Create a form group instance that represents the registration form.
  • Specify every input field that is present in the form, inside the FormGroup constructor.
  • We’ve used curly braces within the parenthesis as we’re passing an object.
  • The object contains every instance of the FormControl that is present in the form.
  • If we wish to set some default value, we can pass it in the FormControl constructor.
  • We’ve used the click event on the button just to display the value of the form.

NOTE: We have a dedicated article on different event handling, you can visit them out.

And lastly, let’s move to the HTML file and link this model that we created.

<div>
   <h1>Registration Form</h1> 
   <form [formGroup]="myform">
    <div>
      <input type="text" placeholder="Enter your name" name="name" formControlName="name">
    </div>
    <div>
      <input type="text" placeholder="Enter your mobile number" name="phone" formControlName="phone">
    </div>
    <div>
      <input type="text" placeholder="Enter your email" name="email" formControlName="email">
    </div>
    <div>
      <input type="text" placeholder="Enter your address" name="address" formControlName="address">
    </div>
    <button type="submit" (click)="clicked(myform.value)">SUBMIT</button>
  </form>
  <br>
  {{formvalue | json}}
</div>
  • On the form tag, we bound “myform” property with the [formGroup] directive.
  • The formControlName directive is used to bind each and every form controls that are present.

Output:

angular reactive forms example

We can also manage formControl values, let’s see how.

clicked(value:any) {
  this.myform.setValue({
    name:"ABC",
    phone:"1236547891",
    email: "[email protected]",
    address:"XYZ"
  })
}

The setValue is the in-built method that is used to update the whole form.

clicked(value:any) {
  this.myform.patchValue({
    name:"ABC",
    phone:"1236547891",
  })
}

The patchValue is the in-built method that is also used to update the form.

NOTE: The key difference between both methods is using setValue we’ve to update the whole structure of the form but while using patchValue we can update our required controls only.

Conclusion

We hope this article has cleared all your concepts on Reactive Form using FormGroup and FormControl. In the upcoming articles, we’ll also learn building forms using FormBuilder and Validator.

Read Next: Angular Form Builder and Validators

Leave a Reply

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