Welcome back to CodeYourCraft! Today, we're diving into a fascinating topic: Angular Router Events. Understanding these events will empower you to create dynamic, interactive applications. Let's get started!
Router Events are Angular's way of notifying components about the current routing state changes. They allow you to respond to these changes, making your applications more responsive and engaging.
NavigationStart event is fired right before Angular initiates a new navigation.import { Router, NavigationStart } from '@angular/router';
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
console.log('NavigationStart:', event);
}
});
}RoutesRecognized event is emitted once Angular recognizes the current route.import { Router, ActivationStart, RoutesRecognized } from '@angular/router';
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof RoutesRecognized) {
console.log('RoutesRecognized:', event);
}
});
}ActivationStart event is emitted when the activation of a route and its associated component begins.import { Router, ActivationStart } from '@angular/router';
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof ActivationStart) {
console.log('ActivationStart:', event);
}
});
}Now that you know about the essential router events, let's see how to respond to them to create more interactive applications.
import { Component } from '@angular/core';
import { Router, ActivationStart, NavigationStart } from '@angular/router';
@Component({
selector: 'app-root',
template: `
<div *ngIf="isNavigating; else content">
Loading...
</div>
<ng-template #content>
<!-- Your content here -->
</ng-template>
`,
})
export class AppComponent {
isNavigating = false;
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.isNavigating = true;
}
if (event instanceof ActivationStart) {
setTimeout(() => {
this.isNavigating = false;
}, 1000);
}
});
}
}What event is fired right before Angular initiates a new navigation?
With this knowledge, you're well on your way to mastering Angular Router Events. In the next lesson, we'll dive deeper into other router events and explore how to use them to create more responsive applications. Stay tuned! 🚀