2

I have seen (this question) and its Answer from @borislemke.

Actaully, tried on Angular2 Demo Application but its not changing Loader Div Background color while Navigating to another route.

My AppComponent is as follows,

import { Component, OnInit }          from '@angular/core';
import { Router, ROUTER_DIRECTIVES, NavigationStart, NavigationEnd, NavigationError, NavigationCancel } from '@angular/router';
import {NgClass} from '@angular/common';

import { DialogService }  from './dialog.service';
import { HeroService }    from './heroes/hero.service';

@Component({
  selector: 'my-app',
  template: `
    <h1 class="title">Component Router</h1>
    <div>Is Navigating -->  {{isLoading}}</div>

    <div [ngClass]="{afterLoad: !isLoading, loading: isLoading }" > Loader Spinner Container </div>

    <nav>
      <a routerLink="/crisis-center" routerLinkActive="active"
         routerLinkActiveOptions="{ exact: true }">Crisis Center</a>
      <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
      <a routerLink="/crisis-center/admin" routerLinkActive="active">Crisis Admin</a>
      <a routerLink="/login" routerLinkActive="active">Login</a>
    </nav>
    <router-outlet></router-outlet>
  `,
  styles:[`
    .loading{
    background-color:red
    }

    .afterLoad{
    background-color:yellow
    }
  `],
  providers:  [
    HeroService,
    DialogService
  ],
  directives: [ROUTER_DIRECTIVES, NgClass]
})
export class AppComponent implements OnInit {
    isLoading: boolean = false;

   constructor(private _router:Router) {}

    ngOnInit() {
        // TODO: assign proper type to event
        this._router.events.subscribe((event: any): void => {
            this.navigationInterceptor(event);
        });
    }

    navigationInterceptor(event): void {
        if (event instanceof NavigationStart) {
            this.isLoading = true;
        }
        if (event instanceof NavigationEnd) {
            this.isLoading = false;
        }
        if (event instanceof NavigationCancel) {
            this.isLoading = false;
        }
        if (event instanceof NavigationError) {
            this.isLoading = false;
        }
    }
}

My plunker is here for live test.

Can anyone help me figuring out the possible cause of failure?

Thanks.

Community
  • 1
  • 1
Jeet
  • 245
  • 1
  • 3
  • 15

1 Answers1

0

Your app is too fast to pick up the navigation changes :)

I added a setTimeout to simulate a slow connection like so:

if (event instanceof NavigationEnd) {
    // this.isLoading = false;
    setTimeout(() => this.isLoading = false, 1000);
}

Try the above code and you can see the background-color changing.

borislemke
  • 8,446
  • 5
  • 41
  • 54