How To Implement Angular Spinner Using Set Interval Time

Introduction

In this article, we are going to see how to implement Angular Spinner on the screen until the data loads from the backend API using HTML and CSS. Here we will be making a simple spinner that will load the data until the API response comes. 

Prerequisite

First, we need to setup the basic angular-cli project using the command:

npm install –g @angular/cli 
ng new test-spinner 
cd test-spinner 

Also, you will need some knowledge for Http to get requests from API and get data from the backend. Another way we have set the interval time is to add the spinner. 

Please follow the code below for the app.component.css file for load spinners styles. 

#spinner {
    -webkit - animation: frames 1 s infinite linear;
    animation: frames 1 s infinite linear;
    background: transparent;
    border: 1.75 vw solid #FFF;
    border - radius: 100 % ;
    border - top - color: #DF691A;
    width: 20 vw;
    height: 20 vw;
    opacity: .6;
    padding: 0;
    position: absolute;
    z - index: 999;
}
@keyframes frames {
    0 % {
        -webkit - transform: rotate(0 deg);
        transform: rotate(0 deg);
    }
    100 % {
        -webkit - transform: rotate(359 deg);
        transform: rotate(359 deg);
    }
}
#pause {
    display: block;
    background: rgba(0, 0, 0, 0.66)
    no - repeat
    0 0;
    width: 100 % ;
    height: 100 % ;
    position: fixed;
    bottom: 0;
    left: 0;
    z - index: 1000;
}

In the app.component.html file, make styles with CSS spinner-test.

<loading *ngIf="isLoading">{{ isLoading }}</loading>  
<div class="jumbotron text-center">  
  <h4>'isLoading' = {{ isLoading }}</h4>  
</div>  
<button class="btn btn-block btn-warning mb-3" (click)="load()">  
  Timeout 2 seconds  
</button> 

Then go to add app.component.ts file the below codes.

import { Component } from '@angular/core'; 
@Component({ 
  selector: 'my-app', 
  templateUrl: './app.component.html' 
}) 
export class AppComponent { 
  isLoading = false; 
  load() : void { 
    this.isLoading = true; 
    setTimeout( () => this.isLoading = false, 2000 ); 
  } 
} 

Once you add the above codes please run the application using ng-serve –open OR npm start command. 

If the application is running, we are able to check the spinner with interval time. Here I have added 2seconds of different for spinner durations.  

Initially set isLoading flag as false. I'm going to click the “Timeout 2 seconds” button and the load () function will call and change the isLoading flag to is true. The interval time is set at 2 seconds and spinner loading has started. After 2 seconds again the isLoading flag changed to false and the spinner has stopped. 

I hope this article is most helpful for you. 


Similar Articles