Ionic 5 Add Ion Loading component in Ionic application

In this Ionic 5/4 tutorial, we’ll learn how to add loader with a message and an animating spinner in an Ionic application using the ion-loading web component. Like native applications, we can show a Loader with a loading animation and a message in Ionic Application using the ion-loading component. Showing a loader in an application…

By.

•

min read

In this Ionic 5/4 tutorial, we’ll learn how to add loader with a message and an animating spinner in an Ionic application using the ion-loading web component.

Like native applications, we can show a Loader with a loading animation and a message in Ionic Application using the ion-loading component. Showing a loader in an application proves very useful and makes application’s communication with an end-user convenient by sharing progress statuses. It creates an overlay to block other user interactions. We can show a loader to indicate if some process is going on like getting data from server or file copy, paste events, etc. Using Ionic loader gives use a message parameter using which we can also show a message indicating the process going on.

Also Read: Ionic Spinner Using Ionic Native Plugin

We’ll implement Ion-loading component in Ionic 5 Angular application and also discuss option available. Ionic loading component is available in @ionic/angular so we don’t need to use any plugin for that. We simply need to import LoadingController in a component or service.

There are also possibilities to customize the ion-loading component with own CSS styles which we’ll discuss later in this tutorial.

 

Also Read:Show Loader Spinner on HTTP Request using Interceptors in Ionic application

 

Let’s get started!

 

 

Update Ionic CLI

Install the latest version of Ionic CLI by running the following npm command.

$ npm install -g @ionic/cli

 

Now create a new Ionic 5 Angular Application with a blank template by running the following command

$ ionic start ionic-ion-loading-app blank --type=angular

 

Move to the application directory

$ cd ionic-ion-loading-app

 

 

# Create a Service for Loader component

In a real-world application, it is always preferred to keep code in a service which we will use at different parts of an application. As a loading component can be used at various components of an application, so its a good practice to keep out ion-loading web components in service.

Run the following ionic generate command to create a new service loader in the services folder.

$ ionic generate service services/loader

Above command will create a new service LoaderService at ~app/services/loader.service.ts location.

// loader.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LoaderService {

  constructor() { }
}

 

 

# Updating LoaderService to use LoadingConroller

To use ion-loading loader, we’ll import the LoadingController then update the constructor() function in the LoderService we just created above

// loader.service.ts
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class LoaderService {

  constructor(
    public loadingController: LoadingController
  ) { }

}

 

 

# Show and Dismiss Loading Component

The LoadingController provides three main methods create(), dismiss() and getTop(). All these methods return Promises using which we can control the behavior of Loading component in the application:

 

Show or Create the Loader

The create() method is called to show Loading overlay using a Promise as shown below:

  showHideAutoLoader() {
    
    this.loadingController.create({
      message: 'This Loader Will Auto Hide in 2 Seconds',
      duration: 2000
    }).then((res) => {
      res.present();

      res.onDidDismiss().then((dis) => {
        console.log('Loading dismissed! after 2 Seconds', dis);
      });
    });

  }

We can also use <strong>async</strong>; <strong>await</strong> approach to use create() method as shown below:

  async showHideAutoLoader() {

    const loading = await this.loadingController.create({
      message: 'This Loader Will Auto Hide in 2 Seconds',
      duration: 2000
    });
    await loading.present();

    const { role, data } = await loading.onDidDismiss();
    console.log('Loading dismissed! after 2 Seconds', { role, data });

  }

The onDisDismiss() callback is triggered after the loader is dismissed.

 

 

Dismiss or Hide the Loader

When we add the duration property with millisecond, then loader shows then hides or dismisses automatically after the duration expires. But if we don’t add duration property then we need to call the dismiss() method to hide the loader.

In some situations, we may need separate show & hide loader methods like in a server API calls, where we want to show Loader when an Http call starts and deliberately hide loader on success or error.

So, if we don’t use duration property then we can use the following methods in our service to call from other pages or services.

// loader.service.ts
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class LoaderService {

  constructor(
    public loadingController: LoadingController
  ) { }

  // This will show then autohide the loader
  showHideAutoLoader() {

    this.loadingController.create({
      message: 'This Loader Will Auto Hide in 2 Seconds',
      duration: 2000
    }).then((res) => {
      res.present();

      res.onDidDismiss().then((dis) => {
        console.log('Loading dismissed! after 2 Seconds', dis);
      });
    });

  }

  // Show the loader for infinite time
  showLoader() {

    this.loadingController.create({
      message: 'Please wait...'
    }).then((res) => {
      res.present();
    });

  }

  // Hide the loader if already created otherwise return error
  hideLoader() {

    this.loadingController.dismiss().then((res) => {
      console.log('Loading dismissed!', res);
    }).catch((error) => {
      console.log('error', error);
    });

  }


}

 

# Using the LoaderService in Home Page

As we are ready with our LoaderService having methods to show/ hide Loaders, now we can use this service by importing it then adding in the class contractor to provide methods for local use

// home.page.ts
import { Component } from '@angular/core';
import { LoaderService } from '../services/loader.service';

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

  constructor(
    private ionLoader: LoaderService
  ) { }

  showLoader() {
    this.ionLoader.showLoader();

    setTimeout(() => {
      this.hideLoader();
    }, 2000);
  }

  hideLoader() {
    this.ionLoader.hideLoader();
  }

}

In the Home Page, we will be adding a button to show loader and hiding it in 2000 ms using a setTimeout, but in an actual application, you may have some other uses.

<ion-button (click)="showLoader()">Show Loader</ion-button>
    <ion-button (click)="hideLoader()">Hide Loader</ion-button>

 

# How to hide loader on tapping on screen?

The create() method uses a property backdropDismisswhich is set to false by default. If this is set to true a user can tap on the screen to hide loader by self.

    this.loadingController.create({
      message: 'Please wait...',
      backdropDismiss:true
    }).then((res) => {
      res.present();
    });

 

 

# Options available:

The create() method can have the following optional properties.

 

<strong>message</strong>: Text to show on the loader with a spinner.

<strong>duration</strong>: Time in milliseconds to autohide loader, if we don’t add this loader will not hide then we can call dismiss method.

<strong>spinner</strong>: We can change the default spinner style to any other one from this available style.

lines

lines-small

bubbles

circles

crescent

dots” or

null

 

backdropDismiss: If this is set to the true user can dismiss loader by tapping anywhere.

cssClass: We can customize loader by adding a class

    this.loadingController.create({
      message: 'This Loader Will Auto Hide in 2 Seconds',
      duration: 20000,
      cssClass:'custom-loader-class'
    }).then((res) => {
      res.present();

      res.onDidDismiss().then((dis) => {
        console.log('Loading dismissed! after 2 Seconds');
      });
    });

 

In global.scss add the following style. We can customize other CSS properties as well

.custom-loader-class{
    --background:#F4B004;
    --spinner-color:#F94701;
}

 

That’s it you can test Ion loader in the browser by running the following command

$ ionic serve --open

The ion-loader component is very to use and adds more value to users in the application.

 

Conclusion: By using the LoadingController we can easily implement a loading component that can be easily used by using a service across the application. We can modify with custom animation and CSS styling as we discussed.

 

One response to “Ionic 5 Add Ion Loading component in Ionic application”

  1. Girija Avatar
    Girija

    •

    Will it possible to add the custom gif image ? I tried and i could not find any solution.

Leave a Reply

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