Create A Sample Angular Project:
For better understanding let's understand the concept by making hands dirty by writing sample examples. So let's create a sample angular project.
If you have prior knowledge of creating Angular Application and configuring Angular Material(UI library) in to project, then free feel to skip this section.
Let's use Angular CLI commands to create a sample project.
Command to install Angular CLI:-
Command To Install Angular CLI globally.This command is like one time installation. If you already have Agnular CLI installed on you system then skip this command. npm install -g @angular/cliCommand to create Angular application:-
ng new your-application-newApplication template looks as below
Now to run the application, open application using any IDE(I'm using Visual Studio Code). Then open the IDE internal Terminal command or open a normal command prompt and set the application root path. Then run the below command.
Command to run application: ng serve
To configure Angular Material UI just run the below command.
ng add @angular/material
Import ReactiveFormModule:
The first basic step to use reactive forms is to import ReactiveFormModule in the app.module.ts file. ReactiveFormModule comes with one of the inbuild angular package '@angular/forms'. ReactiveFormModule provides all objects like 'FormControl', 'FormGroup', 'FormBuilder' which are needed to build reactive forms.
Let's import ReactiveFormModule in the app.module.ts as below
src/app/app.module.ts:
import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ReactiveFormsModule], }) export class AppModule {} // display purpose existing code hidden
FormControl Object:
In reactive forms, FormControl instance gets loaded from the '@angular/forms' package. In reactive forms, an HTML field will have its FormControl instance to establish communication between angular component and HTML. FormControl instance provides many inbuilt features like validating fields, listen to field value changes, identifies the state of the field, etc.
Let's add FormControl instance in the app.component.ts
src/app/app.component.ts:
import { Component} from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ firstName:FormControl = new FormControl(); }Since I'm using material design, I will use material UI form components. So before adding a form input value in Html. Let's import two material modules like 'MatFormFieldModule', 'MatInputModule'.
src/app/app.module.ts:
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; @NgModule({ imports: [ MatFormFieldModule, MatInputModule ], providers: [], bootstrap: [], }) export class AppModule {} // display purpose existing code hiddenNow, let's add the input field and will assign FormControl instance to it.
src/app/app.component.html:
<div> <mat-form-field appearance="fill"> <mat-label>First Name</mat-label> <input matInput [formControl]="firstName"> </mat-form-field> </div>#L4 at this line for [formControl](can be called as FormControlDirective) assigned with 'firstName'(variable holding FormControl instance)
Now start the application and shows the output as below.
FormControl setValue Method:
To update the field value from the FormControl we can use the setValue method.
src/app/app.component.ts:
import { Component, OnInit} from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { firstName:FormControl = new FormControl(); ngOnInit(): void { this.firstName.setValue('naveen'); } }#L15 at this line updating the FormControl name which will reflect on to the field on page load.
Now run application and it shows the output as below.
FormControl Change Detection:
On changing the value on form field in Html, FormControl can respond to those changes. 'valueChanges' is an observable property on FormControl instance that capture the user changes. In real-time scenarios like search content cases, this change detection will help.
src/app/app.component.ts:
import { Component, OnInit} from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { firstName:FormControl = new FormControl(); ngOnInit(): void { this.firstName.valueChanges.subscribe(value => { console.log(value); }) } }#L15-L17 at these lines FormControl valuChanges observable get subscribe to capture the changed value from the user.
Now run the application and shows the output as below.
FormGroup Object:
In reactive forms, FormGroup instance gets loaded from the '@angular/forms' Package. In reactive forms FormGroup act as a container for a set of FormControl instances. So grouping controls can help to separate the existence of multiple numbers of forms on a single page or view.
src/app/app.component.ts:
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 { personFormGroup = new FormGroup({ firstName:new FormControl(''), lastName : new FormControl(''), email: new FormControl(''), phone: new FormControl('') }) }#L10-L15 at these lines FormGroup object created with the collection of FormField objects.
src/app/app.component.html:
<div style="margin:10px;"> <form [formGroup]="personFormGroup"> <div> <mat-form-field class="example-full-width"> <mat-label>First Name</mat-label> <input matInput formControlName="firstName"> </mat-form-field> </div> <div> <mat-form-field> <mat-label>Last Name</mat-label> <input matInput formControlName="lastName"> </mat-form-field> </div> <div> <mat-form-field> <mat-label>Email</mat-label> <input matInput formControlName="email"> </mat-form-field> </div> <div> <mat-form-field> <mat-label>Phone</mat-label> <input matInput formControlName="phone"> </mat-form-field> </div> </form> </div>
- #L2 at this line [formGroup](can be called as FormGroupDirective) defined and assigned 'personFormGroup'(formGroup object).
- All input fields were decorated with 'formControlName'(can be called as FormControlDirective) and assigned 'formcontrol' instances that are inside of the FormGroup.
Nested FormGroup:
FormGroup along with FormControl instances, it can also contain nested FormGroup. Nested FormGroup component gives nice separation for large or complex forms. A nested form state can override the state of main FormGroup(for example if nested form group is an invalid state, then the same state will be applied to the main FormGroup which helps to decide whether to submit the form or not).
src/app/app.component.ts:
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 { personFormGroup = new FormGroup({ firstName:new FormControl(''), lastName : new FormControl(''), email: new FormControl(''), phone: new FormControl(''), address: new FormGroup({ street : new FormControl(''), city: new FormControl(''), state: new FormControl('') }) }) }#L15-L19 at these lines nested FormGroup initialized.
src/app/app.component.html:
<div style="margin:10px;"> <form [formGroup]="personFormGroup"> <div> <mat-form-field class="example-full-width"> <mat-label>First Name</mat-label> <input matInput formControlName="firstName"> </mat-form-field> </div> <div> <mat-form-field> <mat-label>Last Name</mat-label> <input matInput formControlName="lastName"> </mat-form-field> </div> <div> <mat-form-field> <mat-label>Email</mat-label> <input matInput formControlName="email"> </mat-form-field> </div> <div> <mat-form-field> <mat-label>Phone</mat-label> <input matInput formControlName="phone"> </mat-form-field> </div> <div formGroupName="address"> <h4>Address</h4> <div> <mat-form-field> <mat-label>Street</mat-label> <input matInput formControlName="street"> </mat-form-field> <mat-form-field> <mat-label>City</mat-label> <input matInput formControlName="city"> </mat-form-field> <mat-form-field> <mat-label>State</mat-label> <input matInput formControlName="state"> </mat-form-field> </div> </div> </form> </div>#L27 at this line 'address'(nested FormGroup instance variable) assigned to 'formGroupName'(can be called as FormGroupDirective).
Now run the application and shows outputs as below.
FormBuilder Object:
- In reactive form, FormBuilder instance gets loaded from the '@angular/forms' package.
- FormBuilder instance is a factory object which can create instances for FormGroups or FormControls.
- For FormBuilder there is no limit in creating instances for FormGroups or FormControls.
- Using FormBuilder we can avoid explicit initialization of FormGroups or FormControls, this makes form looks clean and simple.
- FormBuilder Object also works with Dependency Injection where we can inject in the component constructor.
src/app/app.component.ts:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { personFormGroup: FormGroup; constructor(private fBuilder: FormBuilder) {} ngOnInit(): void { this.initializeForm(); } initializeForm() { this.personFormGroup = this.fBuilder.group({ firstName:[''], lastName:[''], email:[''], phone: [''], address: this.fBuilder.group({ street:[''], city:[''], state:[''] }) }); } }
- #L13 at this line FormBuilder instance gets injected into the component constructor.
- #L20-30 at these lines FormBuilder instance creating the FormGroup instance, we can observe explicitly initialization of FormControl or FormGroup avoided.
- #L25-29 at these lines FormBuilder instance creating the new FormGroup instance to work as nested FormGroup. From this, we can understand there is no limit in creating FormGroups or FormControls by the FormBuilder instance.
FormGroup setValue:
To update the form with the value we can use the 'setValue' method. But on using the 'setValue' method, we need to update every FormControl value in the FormGroup. So set value will be the ideal technique for the initial page load, where we fetch data from the database(using APIs) to update the entire form.
Let's update the code to use the 'setValue' method as below.
src/app/app.component.ts:
setValueMethod(){ this.personFormGroup.setValue({ firstName:'Naveen', lastName: 'Bommidi', email:'bommidi@gmail.com', phone:'1234567890', address:{ street:'Arunoday colony', city:'hyderabad', state:'Telangana' } }); }#L2-L12 at these lines you can observe updating data to the entire sample form. We can observe using the 'setValue' method need to update every FormControl and FromGroup.
Let's create a test button to update all form values.
src/app/app.component.html:
<div style="margin:10px;"> <form [formGroup]="personFormGroup"> <!-- display purpose code hidden --> </form> <div> <button mat-raised-button color="primary" (click)="setValueMethod()">Update All Form values</button> </div> </div>#L6 at this line added a button and it clicks event registered with 'setValueMethod'.
Now let's run the application and output shows as below.
Now on clicking 'Update All Form values' button form get populated with data and shows as below.
FormGroup patchValue:
Since the setValue method only works for updating entire form values, it won't be an ideal technique to use in most cases. So update partially or whatever form controls to be updated then we should use 'patchValue'. For the 'patchValue' method there are no rules to update all form fields, it can update whatever field it wants.
Let's create a simple patchValue method as follows.
src/app/app.component.ts:
patchValueMethod(){ this.personFormGroup.patchValue({ firstName:'Naveen', address:{ city:'Hyderabad' } }); }#L2-L7 at these lines FormGroup data patching for only 2 form controls.
Let's add a test button to invoke this patchValue method as follows.
src/app/app.component.html:
<div style="margin:10px;"> <form [formGroup]="personFormGroup"> <!-- code hidden for display purpose --> </form> <div> <button mat-raised-button color="primary" (click)="setValueMethod()">Update All Form values</button> <button mat-raised-button color="primary" (click)="patchValueMethod()">Update Only Specific Fields</button> </div> </div>#L7 at this line button added and it clicks event to bind to 'patchValueMethod'.
Now let's run the application and output shows as below.
Now click on button and output show as below.
Add Validation:
In reactive forms configuring validation is so simple and easy. Validation to a reactive form can be done at the time of form initialization or dynamically. Here we going to add validation at the time of initializing form.
Using 'Validators' instance which will get loaded from '@angular/forms' package. 'Validators' instance provide default validation like 'required', 'email', 'min length', 'max length', etc.
Let's update our form initialized method to register our validation as follows.
src/app/app.component.ts:
import { Validators } from '@angular/forms'; initializeForm() { this.personFormGroup = this.fBuilder.group({ firstName:['',Validators.required], lastName:[''], email:['', [Validators.required, Validators.email]], phone: [''], address: this.fBuilder.group({ street:[''], city:[''], state:[''] }) }); }
- #L5 at this line number 'Validators.required' validation added to firstName FormControl.
- #L7 at this line number array of Validators like 'required' and 'email' validations added to the email FormControl.
src/app/app.component.ts:
onSubmit(){ if(this.personFormGroup.valid){ var formData = { name: this.personFormGroup.controls.firstName.value, lastName : this.personFormGroup.controls.lastName.value, email : this.personFormGroup.controls.email.value, phone: this.personFormGroup.controls.phone.value, street: this.personFormGroup.get('address.street').value, city: this.personFormGroup.get('address.city').value, state: this.personFormGroup.get('address.state').value } // need to write post api call to save data } }Here this method will execute on submitting a valid form. Here you can also observe the way to fetch the data from FormControl and also from nested FormGroupControl.
Now let's add form submit button and bind this 'onSubmit()' method to the form as below
src/app/app.component.html:
<div style="margin:10px;"> <form [formGroup]="personFormGroup" (ngSubmit)="onSubmit()"> <!-- code hidden for display purpose --> <div> <button mat-raised-button color="primary" >Submit Form</button> </div> </form> </div>
- #L2 at this line using angular (onSubmit) form event bounded to our custom 'onSubmit()' method. so this (onSubmit) gets fired on the clicking a button inside the form.
- #L5 at this line added button to invoke form submit.
Click on the submit button, form validation executes and the output shows as below.
Wrapping Up:
Hopefully, I think this article delivered some useful information on angular reactive forms. I love to have your feedback, suggestions, and better techniques in the comment section below.
Your articles are very precise. Will be very helpful for beginners and even experienced people for simplicity of the content. Keep up the good work.
ReplyDelete