Ionic 4 – Reactive Forms

Angular, which is the default framework for starting Ionic applications provide 2 kinds of forms, reactive forms, and template-driven forms.

In this post, we will only discuss the implementation of Reactive Forms in an Ionic 4 app.

Reactive Forms

Reactive forms provide a model-driven approach to handling form inputs whose values change over time.

https://angular.io/guide/reactive-forms

Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time. Each change to the form state returns a new state, which maintains the integrity of the model between changes. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.

https://angular.io/guide/reactive-forms
Login screen validation using Reactive Forms

Let’s try to take an example of a login screen. We will be using Reactive Forms here.

Step 1 – app.module.ts

Importing the ReactiveFormsModule in app.module.ts

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

Add the ReactiveFormsModule to the imports array of app.module.ts

@NgModule({
   declarations: [AppComponent],
   entryComponents: [],
   imports: [
     ...
     ReactiveFormsModule
     ...
   ],

Step 2 – Create a module called login

In the login.module.ts, import the following:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Add the following modules to the imports array of login.module.ts

@NgModule({
   imports: [
     ...
     FormsModule,
     ReactiveFormsModule,

Step 3 – Use FormBuilder and FormControl

Listing of login.page.ts

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
 @Component({
   selector: 'app-login',
   templateUrl: 'login.page.html',
   styleUrls: ['login.page.scss'],
 })
 export class LoginPage {
   public loginForm: FormGroup;
   constructor(private storage: Storage, 
               private formBuilder:FormBuilder){
     this.loginForm = this.formBuilder.group({
       username: new FormControl('', Validators.compose([
         Validators.required
       ])),
       password: new FormControl('', Validators.compose([
         Validators.required
       ]))
     });
   }
 onClickSubmit() {
     console.log('Start login with: ' 
                 + this.loginForm.value.username + ':' 
                 + this.loginForm.value.password);
   }
 }

We create a loginForm(FormGroup) to hold FormControls like username and password. You can also add any number of validations that you need.

There’s also a function onClickSubmit to submit data when the validations are done.

Step 4 – Creating the form

Listing of login.page.html

<ion-header>
   <ion-toolbar color="primary">
     <ion-title>
       Ionic 4 App
     </ion-title>
   </ion-toolbar>
 </ion-header>
 <ion-content padding="true">
   <ion-row class="ion-justify-content-center">
     <ion-col size-sm="12" size-lg="5">
       <div class="ion-padding login-card">
         <ion-card>
           <ion-card-header color="secondary" class="login-card-header">
             <ion-card-title>Login</ion-card-title>
           </ion-card-header>
           <ion-card-content>
             <form (ngSubmit)="onClickSubmit()" padding-right [formGroup]="loginForm">
               <ion-item lines="inset">
                 <ion-label position="floating">Username</ion-label>
                 <ion-input  formControlName="username"></ion-input>
               </ion-item>
               <ion-item lines="inset">
                 <ion-label position="floating">Password</ion-label>
                 <ion-input formControlName="password" type="password"></ion-input>
               </ion-item>
               <ion-item lines="none" class="ion-item-right-margin">
                 <ion-button size="default" slot="end" type="submit" [disabled]="!loginForm.valid">Submit</ion-button>
               </ion-item>
               </form>
           </ion-card-content>
         </ion-card>
       </div>
     </ion-col>
   </ion-row>
 </ion-content>

Username and password input fields have a named FormControlName attribute which is defined in the login.page.ts.

How does it work?

Whenever the value in either text fields are changed, the validations are automatically applied, and loginForm.valid value changes. This field in turn, controls the Submit button.

The loginForm is synchronously updated as soon as any changes are detected on the fields inside the FormGroup.