Angular2: Using loader/spinner as angular service in Angular 2 application


Since loader is essential component for any connected web application, we have couple of spinner component available in market for angular2, I am using ng-lightning spinner…

For custom spinner without using any third party lib, then checkout my other post :
Angular2: Using custom loader / spinner as service in Angular 2 application


Since spinner is used throughout the application, so its better to define it once in index.html and then try to enable/disable through component code. I am also using BehaviorSubject object in service, which is way more awesome and better then observable in many cases, Behavior Subject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. In plain words the variable controlling enabling and disabling the spinner in index.html can be set and observed in service using BehaviorSubject object.

Index/main-component.html code:

<span *ngIf="objLoaderStatus">
      <ngl-spinner size="large" type="brand" container="true"></ngl-spinner>


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

import { LoaderService } from './shared/service/loader.service';

    selector: 'my-app',
    templateUrl: '../../Scripts/app/app.component.html'

export class AppComponent implements OnInit{
    objLoaderStatus: boolean;

        private loaderService: LoaderService) {
        this.objLoaderStatus = false;

    ngOnInit() {
        this.loaderService.loaderStatus.subscribe((val: boolean) => {
            this.objLoaderStatus = val;


import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class LoaderService {
    public loaderStatus: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

    displayLoader(value: boolean) {;


ngOnInit() {
            this.loaderService.displayLoader(true); // enable spinner
            //do some fancy caluclation
            this.loaderService.displayLoader(false); // disable spinner





Please include ng-lightning package in app.module.ts

import { NglModule } from 'ng-lightning/ng-lightning';

One thought on “Angular2: Using loader/spinner as angular service in Angular 2 application

  1. Scot Seyfert

    This information is magnificent. I understand and respect your clear-cut points. I am impressed with your writing style and how well you express your thoughts.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s