Angular 6 Loading Spinner Example

Angular 6 Loading Spinner Example is the today’s main topic. In the real-time example, when we send a network request to the server, while we get a response, we need to display the spinner or any loader to the user. It is the best practice for user experience. So in this example, I will show you how you can use loader or spinner while getting the response from the server.

Angular 6 Loading Spinner Example

Okay, first we need to install Angular 6 using Angular CLI.

#1: Install Angular 6

If you have not installed Angular CLI globally on your machine, then install it using the following command.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Now, create a local project using the following command.

ng new angularspinner

#2: Install rxjs-compat library.

At the time of this data, third-party libraries do not support the RxJS 6. We need to fill the gap between Angular 6 and third-party libraries. So, to fill the bridge between Angular 6 application and third-party libraries, we need to install the rxjs-compat library. That is it.

npm install rxjs-compat --save

#3: Install Bootstrap 4.

Type the following command.

npm install bootstrap --save

After that go to the src folder and open styles.css file and import the bootstrap.min.css file.

@import "~bootstrap/dist/css/bootstrap.min.css"

#4: Install Angular epic spinners.

Type the following command to install the angular epic spinner library.

npm install angular-epic-spinners

# or

yarn add angular-epic-spinners

Now, add the AtomSpinnerModule inside an app.module.ts file. Import each spinners’ module into your module file and use the spinner component anywhere.

// app.module.ts

import {AtomSpinnerModule} from 'angular-epic-spinners'
  
@NgModule({
  imports: [AtomSpinnerModule]
})

Okay, now we just need to use this component in any html file we want.

For example, let us write this component inside src >> app >> app.component.html file.

<!-- app.component.html -->

<div *ngIf = "title">
  <app-atom-spinner
    [animationDuration]="1000"
    [size]="60"
    [color]="'#ff1d5e'">
  </app-atom-spinner>
</div>

So, here, we have written the component <app-atom-spinner>, but we have put one condition.

If the title property is set to true then and then we display the spinner component. Otherwise, it will not render it.

Now, we can set this logic inside an app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  display = false;
}

Now go to the browser at http://localhost:4200/

We see nothing because we have set the display property to false.

Now, set it to true and again go to the browser.

You can see something like this with animating.

Angular 6 Loading Spinner Example

 

So, finally, we have displayed the spinner inside our Angular application.

#5: Create JSON server.

We need the fake data to work with that is why I am using one package called json-server for this tutorial. 

yarn global add json-server

# or

npm install -g json-server

Create a folder inside root called data and in that directory, create a file called db.json. Add the following json data inside a db.json file.

{
    "results": [
    {
        "id": "1",
        "name": "RDJ",
        "movies": "100"
    },
    {
        "id": "2",
        "name": "Tom Holland",
        "movies": "3"
    },
    {
        "id": "3",
        "name": "Benedict Cumberbatch",
        "movies": "10"
    },
    {
        "id": "4",
        "name": "Chris Hemsworth",
        "movies": "30"
    },
    {
        "id": "5",
        "name": "Chris Evans",
        "movies": "20"
    }]
}

Now, start the JSON server using the following command.

json-server --watch data/db.json --port 4000

Now that we have our server running, we can feed the data to our Angular application.

Our JSON server is started at port: 4000 and URL is: http://localhost:4000/results

#6: Setup HttpClient.

The angular framework is bundled with HttpClient library by default. So, we need to import the module inside an app.module.ts file, and we are ready to go.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
  BrowserModule,
  AtomSpinnerModule,
  HttpClientModule
],

Now, inside app folder, create one file called User.ts. It is an interface that contains the property with its datatype we expect from the server.

// User.ys

export interface User {
    id: Number;
    name: String;
    movies: Number;
}

Create a service file by typing the following command.

ng g s user --spec=false

Write the following code inside a user.service.ts file. It will fetch the data from the json server.

// user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getUsers() {
    return this
            .http
            .get(`${this.url}/results`);
        }
}

Now, include both User.ts and UserService.ts file inside an app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './User';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  display = false;
  users: User[];

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService
      .getUsers()
      .subscribe((data: User[]) => {
          this.users = data;
        });
  }
}

Next step is to write the following code inside an app.component.html file.

<!-- app.component.html -->

<div *ngIf = "display">
  <app-atom-spinner
    [animationDuration]="1000"
    [size]="60"
    [color]="'#ff1d5e'">
  </app-atom-spinner>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Movies</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.movies }}</td>
    </tr>
  </tbody>
</table>

Now, save the file, and you can see the data on the home page of our Angular Application.

#7: Create Delay to display spinner.

In pure JavaScript, we use the setTimeout event to display spinner and then after the timeout complete; we can see the data. So our final code on app.component.ts file looks like below.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './User';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  display = false;
  users: User[];

  constructor(private userService: UserService) {
    this.fetchUsers = this.fetchUsers.bind(this);
  }

  ngOnInit() {
    this.display = true;
    setTimeout(this.fetchUsers, 2000);
  }
  fetchUsers() {
    this.userService
      .getUsers()
      .subscribe((data: User[]) => {
        this.users = data;
        this.display = false;
      });
    }
}

We need to bind this. Otherwise, we can not access the scope, and we fail to fetch the data.

Now, you can see till 2 seconds, we see the loading spinner, and after that, we can see our data.

#8: Different spinners.

You can find more spinners on this link: https://github.com/hackafro/angular-epic-spinners

You can easily configure spinners’ size, color and animation speed.

<app-flower-spinner
  [animationDuration]="2500"
  [size]="70"
  [color]="'#ff1d5e'"
></app-flower-spinner>

<app-pixel-spinner
  [animationDuration]="2000"
  [pixelSize]="70"
  [color]="'#ff1d5e'"
></app-pixel-spinner>

<app-hollow-dots-spinner
  [animationDuration]="1000"
  [dotSize]="15"
  [dotsNum]="3"
  [color]="'#ff1d5e'"
></app-hollow-dots-spinner>

<app-intersecting-circles-spinner
  [animationDuration]="1200"
  [size]="70"
  [color]="'#ff1d5e'"
></app-intersecting-circles-spinner>

<app-orbit-spinner
  [animationDuration]="1200"
  [size]="55"
  [color]="'#ff1d5e'"
></app-orbit-spinner>

<app-radar-spinner
  [animationDuration]="2000"
  [size]="60"
  [color]="'#ff1d5e'"
></app-radar-spinner>

<app-scaling-squares-spinner
  [animationDuration]="1250"
  [size]="65"
  [color]="'#ff1d5e'"
></app-scaling-squares-spinner>

<app-half-circle-spinner
  [animationDuration]="1000"
  [size]="60"
  [color]="'#ff1d5e'"
></app-half-circle-spinner>

<app-trinity-rings-spinner
  [animationDuration]="1500"
  [size]="66"
  [color]="'#ff1d5e'"
></app-trinity-rings-spinner>

<app-fulfilling-square-spinner
  [animationDuration]="4000"
  [size]="50"
  [color]="'#ff1d5e'"
></app-fulfilling-square-spinner>

<app-circles-to-rhombuses-spinner
  [animationDuration]="1200"
  [circlesNum]="3"
  [circleSize]="15"
  [color]="'#ff1d5e'"
></app-circles-to-rhombuses-spinner>
    
<app-semipolar-spinner
  [animationDuration]="2000"
  [size]="65"
  [color]="'#ff1d5e'"
></app-semipolar-spinner>
    
<app-self-building-square-spinner
  [animationDuration]="6000"
  [size]="40"
  [color]="'#ff1d5e'"
></app-self-building-square-spinner>
    
<app-swapping-squares-spinner
  [animationDuration]="1000"
  [size]="65"
  [color]="'#ff1d5e'"
></app-swapping-squares-spinner>

<app-fulfilling-bouncing-circle-spinner
  [animationDuration]="4000"
  [size]="60"
  [color]="'#ff1d5e'"
></app-fulfilling-bouncing-circle-spinner>

<app-fingerprint-spinner
  [animationDuration]="1500"
  [size]="64"
  [color]="'#ff1d5e'"
></app-fingerprint-spinner>

<app-spring-spinner
  [animationDuration]="3000"
  [size]="60"
  [color]="'#ff1d5e'"
></app-spring-spinner>

<app-atom-spinner
  [animationDuration]="1000"
  [size]="60"
  [color]="'#ff1d5e'"
></app-atom-spinner>

<app-looping-rhombuses-spinner
  [animationDuration]="2500"
  [rhombusSize]="15"
  [color]="'#ff1d5e'"
></app-looping-rhombuses-spinner>

<app-breeding-rhombus-spinner
  [animationDuration]="2000"
  [size]="65"
  [color]="'#ff1d5e'"
/><app-breeding-rhombus-spinner>

Finally, Angular 6 Loading Spinner Example is over. Thanks for taking.

Post Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments