In Angular, By default, all modules are loaded as soon as the applications load, irrespective of which modules are immediately necessary and which are not.
Why Lazy-loaded Modules
In the case of applications with many routes, these modules would eventually increase initial load time and consequently bad user experience. To prevent large load time we prefer lazy-loaded modules to minimize initial load time as well as bundle size. Every module is of different sizes as well as the network conditions, which will take different times to load. For a better user experience, showing loader would definitely be a good idea!
Loader code
app.component.html
<router-outlet>
<span class="loader" *ngIf="isLoading"></span>
</router-outlet>
app.component.css
.loader {
display: inline-block;
width: 40px;
height: 40px;
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
top: 50%;
transform: translateY(-50%);
}
.loader:after {
content: " ";
display: block;
width: 100px;
height: 100px;
border-radius: 50%;
border: 5px solid #000;
border-color: #000 transparent #000 transparent;
animation: loader 1.2s linear infinite;
}
@keyframes loader {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
app.component.ts
import { Component } from '@angular/core';
import { Router, RouteConfigLoadStart, RouteConfigLoadEnd, RouterEvent } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isLoading: boolean = false
constructor(router: Router) {
router.events.subscribe(
(event: RouterEvent): void => {
if (event instanceof RouteConfigLoadStart) {
this.isLoading = true;
} else if (event instanceof RouteConfigLoadEnd) {
this.isLoading = false;
}
}
);
}
}
The actual source code is here. The Loader part is
<span class="loader" *ngIf="isLoading"></span>
which has a condition to show and hide based on isLoading boolean. The last part is app.component.ts where we have added the following code block:
router.events.subscribe(
(event: RouterEvent): void => {
if (event instanceof RouteConfigLoadStart) {
this.isLoading = true;
} else if (event instanceof RouteConfigLoadEnd) {
this.isLoading = false;
}
}
);
Here we are subscribed to router events and switching isLoading based on RouteConfigLoadStart and RouteConfigLoadStart.
Hope this would be useful, see you guys soon 👋.
Top comments (0)