Show Loading Screen While Navigating Between Routes in Angular 2
A common requirement in Angular applications is displaying a loading screen or indicator while navigating between routes. By harnessing the Navigation Events provided by Angular's Router, we can toggle the visibility of a loading screen according to the navigation state.
Using Subscription to Navigation Events:
In the root AppComponent, subscribe to the router's events. When a NavigationStart event occurs, display the loading screen. When a NavigationEnd event is emitted, hide the loading screen. Additionally, handle NavigationCancel and NavigationError events to ensure the loading screen is hidden in case of failed route transitions.
import { Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'; @Component({ /* ... */ }) export class AppComponent { loading = true; constructor(private router: Router) { this.router.events.subscribe((event: Event) => { this.navigationInterceptor(event); }); } navigationInterceptor(event: Event): void { if (event instanceof NavigationStart) { this.loading = true; } else if (event instanceof NavigationEnd) { this.loading = false; } } }
In the root component's template, display the loading screen using *ngIf directive.
<div *ngIf="loading" class="loading-overlay"> <!-- Add your loading indicator here --> </div>
Performance Optimization:
For better performance, Angular's NgZone and Renderer capabilities can be leveraged instead of the *ngIf directive. This avoids Angular's change detection mechanism when updating the spinner's visibility.
@ViewChild('spinnerElement') spinnerElement: ElementRef; constructor(private router: Router, private ngZone: NgZone, private renderer: Renderer) { router.events.subscribe(this._navigationInterceptor); } private _navigationInterceptor(event: Event): void { if (event instanceof NavigationStart) { this.ngZone.runOutsideAngular(() => { this.renderer.setElementStyle(this.spinnerElement.nativeElement, 'opacity', '1'); }); } else if (event instanceof NavigationEnd) { this._hideSpinner(); } } private _hideSpinner(): void { this.ngZone.runOutsideAngular(() => { this.renderer.setElementStyle(this.spinnerElement.nativeElement, 'opacity', '0'); }); }
In the root component's template, remove the *ngIf directive and directly reference the spinner element.
<div #spinnerElement>
The above is the detailed content of How to Show a Loading Screen During Route Navigation in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!