In Angular 2, displaying a loading screen during route transitions is useful for providing user feedback and enhancing the application's perceived performance. This can be achieved by utilizing Navigation Events provided by the Angular Router.
The provided solution involves subscribing to these events and making appropriate UI changes. However, it's important to consider additional events like NavigationCancel and NavigationError to halt the spinner in case a transition fails. Here's the implementation in Angular 2's TypeScript component system:
import { Router, Event as RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router' @Component({}) export class AppComponent { loading = true; constructor(private router: Router) { this.router.events.subscribe(e => { this.navigationInterceptor(e); }) } navigationInterceptor(event: RouterEvent): void { if (event instanceof NavigationStart) { this.loading = true; } if (event instanceof NavigationEnd) { this.loading = false; } if (event instanceof NavigationCancel || event instanceof NavigationError) { this.loading = false; } } }
For the corresponding view, add the spinner element and conditionally display it using the *ngIf directive:
<div class="loading-overlay" *ngIf="loading"> <md-progress-bar mode="indeterminate"></md-progress-bar> </div>
For performance optimization, consider leveraging the Angular NgZone and Renderer to toggle the spinner element's visibility, which bypasses change detection:
import { NgZone, Renderer, ElementRef, ViewChild } from '@angular/core'; @Component({}) export class AppComponent { @ViewChild('spinnerElement') spinnerElement: ElementRef; constructor(private router: Router, private ngZone: NgZone, private renderer: Renderer) { router.events.subscribe(this._navigationInterceptor); } private _navigationInterceptor(event: RouterEvent): void { if (event instanceof NavigationStart) { this.ngZone.runOutsideAngular(() => { this.renderer.setElementStyle( this.spinnerElement.nativeElement, 'opacity', '1' ); }) } if (event instanceof NavigationEnd) { this._hideSpinner(); } if (event instanceof NavigationCancel || event instanceof NavigationError) { this._hideSpinner(); } } private _hideSpinner(): void { this.ngZone.runOutsideAngular(() => { this.renderer.setElementStyle( this.spinnerElement.nativeElement, 'opacity', '0' ); }) } }
In the corresponding view, use a direct reference to the element:
<div class="loading-overlay" #spinnerElement>
The above is the detailed content of How to Implement Loading Screens During Route Navigation in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!