Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Ionic form example and Ionic form validation – step by step tutorial

The form is the most commonly used element in web and mobile applications. In this article, we will learn about types of Ionic forms and how to validate them. We will focus purely on how to handle user input, primarily via
the use of forms. Forms are used for everything from logging in and registering to more complex use cases. When dealing with form is not only about form element but we also have data binding, form validation, form state and error handling.

In this article, we will explore different types of forms we can use in Ionic angular. How we can validate the Ionic form and demonstrate an example of a different form. Let’s get started.

Different types of an Ionic form in Ionic Angular.

In an Ionic Angular, Angular offers two approaches to building and handling ionic form. HTML comes with a number of form elements by default such as inputs, selects, and buttons. An Angular provides a way to use these native elements and add some power to them. There are two primary mechanisms to work with forms in Angular.

  • Template drive form (FormsModule).
  • Reactive form (ReactiveFormsModule).

Setting and creating project for Ionic form example

We can build almost any form with an Angular template—login forms, contact forms, and pretty much any business form. Let demonstrate a template-driven approach by implementing an example. In a template-driven approach, we can easily set up our form in the template. We need to import FormModule to get the template drive approach to get this form creation by Angular to work.

We build the HTML template and add a few directives to specify additional information (such as validation rules). Angular takes charge of building the model objects for us behind the scenes: the underlying forms, form groups, and controls. So we can think of form elements in a template as serving as a selector for some angular directive.

ionic start myForm blank --type=angular
ionic form example

Import FormModule in our component module.

We need to import FormModule in our component module. It provides required providers and directives for template-driven forms to work. Angular will automatically create a form that represents the JavaScript object of form when it detects a form element in a template of a component. By default, while create page will have FormModule, if it is not present then we need to import FormModule. Let edit the home.module.ts file

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule
  ],
  declarations: [HomePage]
})
export class HomePageModule {}

Add Form element in our page template

We will create a simple registration page to demonstrate a template-driven approach. If we have a button in a form element where we called the form to submit method directly. The default behavior of HTML will be triggered. This button will submit the form and it will also trigger a javascript submit an event build in HTML. We can take advantage of using the angular ngSubmit directive, adding directly to the form element. This directive gives only one event in which we can listen whenever the form is submitted.

We can place ngSubmit directive on the form. The event made available by the ngSubmit directive will be fired whenever this form is submitted, so whenever this default behavior is triggered.

<ion-header [translucent]="true">
  <ion-toolbar color="primary">
    <ion-title>
      Ionic registeration form
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <form #f="ngForm" (ngSubmit)="loginForm(f)" novalidate>
    <ion-list>
      <ion-item>
        <ion-label>Username</ion-label>
        <ion-input [(ngModel)]="data.username" #nameCtrl="ngModel" name="username" required></ion-input>
      </ion-item>
      <ion-item *ngIf="!nameCtrl.valid && nameCtrl.touched">
        <ion-text color="danger">Name is required</ion-text>
      </ion-item>

      <ion-item>
        <ion-label>Password</ion-label>
        <ion-input type="password" [(ngModel)]="data.password" #passwordCtrl="ngModel" name="password" required>
        </ion-input>
      </ion-item>
      <ion-item *ngIf="!passwordCtrl.valid && passwordCtrl.touched">
        <ion-text color="danger">Password is required</ion-text>
      </ion-item>
      <ion-button type="submit" expand="block" fill="outline" [disabled]="!f.valid">
        Login
      </ion-button>
    </ion-list>

    <div class="ion-padding" *ngIf="f.valid">
      Form username: {{ f.value.username }}<br />
      Form password: {{ f.value.password }}
    </div>
  </form>
</ion-content>

The ngModel without parenthesis is enough to tell angular this input is actually control of my form. 

On our home page, we have a template reference variable on form #f=”ngForm”. It tells angular to give access to this form which we have created in our template component. This is how we get access to the form, to this javascript object created by Angular automatically.

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  data = { username:'', password: ''};

  constructor() { }

  loginForm(form: NgForm) {
    console.log(form);
  }
}

Ionic form validation

We have local reference #f=”ngForm” in our home template. The ngForm gives access to form object of javascript created by an Angular. It stores state information for the form, including the following.

  • Values object containing all the controls inside the form.
  • Groups of fields in the form.
  • Validators value objects like dirty, error, touched, etc for Validation.

We can get form value by using template form reference value as

<form #f="ngForm" (ngSubmit)="loginForm(f)" novalidate>
  <ion-list>
 	....
  </ion-list>

  <div class="ion-padding" *ngIf="f.valid">
      Form username: {{ f.value.username }}<br />
      Form password: {{ f.value.password }}
  </div>
</form>

Below image is screenshot of our Ionic template form validation.

Once w have our form reference, we can use form reference to validate our form and we have already added form validation code. Let focus on one form field and here is code for form validation.

<form #f="ngForm" (ngSubmit)="loginForm(f)" novalidate>
 <ion-item>
   <ion-label>Username</ion-label>
   <ion-input [(ngModel)]="data.username" #nameCtrl="ngModel" name="username" required> </ion-input>
   </ion-item>
      
   <ion-item *ngIf="!nameCtrl.valid && nameCtrl.touched">
     <ion-text color="danger">Name is required</ion-text>
   </ion-item>
      
   .....
 </form>

Like form reference and we can add form element reference on each field on the form. In our case, we have used nameCtrl reference username input and we can check if it is valid or invalid and touched or not. Based on the status of each element we can validate the form element.

We can also add placeholder for form element by using placeholder property on form element.

<ion-input [(ngModel)]="data.username" #nameCtrl="ngModel" name="username" placeholder="User name"></ion-input>

ngModel:
Angular will not automatically detect this input in this form and we may also need to control the form element. In input, we have to add the ngModel directive from the two-way data binding. This will tell angular that input is actually control of the form. The ngModel is a directive made available in the formModule.

Name attribute:
By using the name attribute we can specify the name of the control in a form. To recognized input as a control in a form, we need to give angular the name of control by adding name attribute on input. The name is the default attribute you can add to any HTML control.

Setting and patching form elements values.

In the template-driven form approach, we have used viewChild on the form to get access form in component typescript. The setValue method allows us to set the value of the whole form, we need to pass Javascript object exactly representing our form.

@viewChild('f') loginForm: NgForm;

someMethod() {
   this.loginForm.setValue({
      username: 'edupala',
      password: ''
    });
}

The patchValue method to set value only to specific elements on the form, we need to pass form elements in a Javascript object. It will not overwrite other value which we have not to specify in patchValue method.

@viewChild('f') loginForm: NgForm;

someMethod() {
    this.loginForm.patchValue({
      userName: 'edupala'
    });
}

Angular form Control status CSS classes for ionic form validation

Angular adds a couple of classes on form elements to indicate form element validation status. Angular automatically mirrors many control properties onto the form control element as CSS classes. We can use these classes to style form to show warnings or style the form elements according to the state of the form element. The following classes are currently supported.

  • pristine: Data entry has not been touched.
  • dirty: (Input field has been interacted with).
  • touched: (Input field has received focus).
  • valid: (Data entry has passed validation)
  • invalid: (Data entry has not passed validation)
  • errors: Where data entry have not satisfied the rule

We can add red color on invalid field label we need to add the following style in global.scss as.

/** For form invalid field for Ionic Angular*/
.ion-invalid.ion-touched ion-label {
    color: var(--ion-color-danger);
}

/** For form invalid field for Angular*/
input.ng-invalid.ng-touched{
    border: 1px solid red;
}

Conclusion
We have discussed the Ionic Angular form type, the styling of a form validation error, and demonstrate the Ionic template drive form example on the registration form. I have you have got some idea on the Ionic angular form.

Related posts

Ionic form example and Ionic form validation – step by step tutorial

Leave a Reply

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

Scroll to top