Angular 2 router event listener
new router
constructor(router:Router) {
router.events.subscribe(event:Event => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
});
}
oldInject the Router and subscribe to route change events
import {Router} from 'angular2/router';
class MyComponent {
constructor(router:Router) {
router.subscribe(...)
}
}
NOTEFor the new router, don't forget to import NavigationStart
from router
module
import { Router, NavigationStart } from '@angular/router';
because if you don't import it instanceof
will not work and an error NavigationStart is not defined
will rise.See also
- https://angular.io/docs/ts/latest/api/router/index/Router-class.html
- How to detect a route change in Angular 2?
Angular Router Event Name
Event
is only the base class.
The concrete event values are one of
- NavigationStart
- NavigationEnd
- NavigationCancel
- NavigationError
- RoutesRecognized
constructor(router:Router) {
router.events
.filter(event => event instanceof NavigationStart)
.subscribe((event:NavigationStart) => {
// You only receive NavigationStart events
});
See also How to detect a route change in Angular 2? Angular: How to globally listen to router events
This is what I use:
import { Component } from '@angular/core';
import { Router, Event, NavigationStart, NavigationEnd, NavigationError, NavigationCancel } from '@angular/router';
@Component({
selector: 'mh-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
loading: boolean = true;
constructor(private router: Router) {
router.events.subscribe((routerEvent: Event) => {
this.checkRouterEvent(routerEvent);
});
}
checkRouterEvent(routerEvent: Event): void {
if (routerEvent instanceof NavigationStart) {
this.loading = true;
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.loading = false;
}
}
}
How to detect a route change in Angular?
In Angular 2 you can subscribe
(Rx event) to a Router instance.
So you can do things like
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*whatever*/)
}
}
Edit (since rc.1)class MyClass {
constructor(private router: Router) {
router.changes.subscribe((val) => /*whatever*/)
}
}
Edit 2 (since 2.0.0)see also : Router.events doc
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
Angular 2 How to detect back button press using router and location.go()?
I don't know if the other answers are dated, but neither of them worked well for me in Angular 7. What I did was add an Angular event listener by importing it into my component:
import { HostListener } from '@angular/core';
and then listening for popstate
on the window
object (as Adrian recommended): @HostListener('window:popstate', ['$event'])
onPopState(event) {
console.log('Back button pressed');
}
This worked for me. Angular Router Events: NavigationEnd -- How to filter only the last event
Okay, after reading through the posted articles above and rethinking what I really want to achieve I found out that my approach was definitely too complicated. Because actually I only need access to the currently called route. And so I started from scratch and came across this small but very effective solution:
this.router.events.subscribe(value => {
console.log('current route: ', this.router.url.toString());
});
Thanks to all who shared a comment in oder to support me! It helped al lot as I was able to tie up loose ends. How to trace routing in Angular 2?
You can pass in a second argument with options:
imports: [
RouterModule.forRoot(
routes,
{ enableTracing: true } // <-- debugging purposes only
)
]
Angular will then log all events to the browser's console, per the documentation:enableTracing?: boolean
When true, log all internal navigation events to the console. Use for debugging.
In angular 2 how do you detect route changes
In the new router it's
this.router.events.subscribe(...)
See also Angular 2 router event listener
Related Topics
How to Deeply Merge Two Object Values by Keys
Do Browsers Parse JavaScript on Every Page Load
Add Commas to a Number in Jquery
Dynamic Require in Requirejs, Getting "Module Name Has Not Been Loaded Yet for Context" Error
How to Use Local Storage in Angular
Viewing All the Timeouts/Intervals in JavaScript
Can Promises Have Multiple Arguments to Onfulfilled
Jquery "On Create" Event for Dynamically-Created Elements
JavaScript Summing Large Integers
Why Is There a 'Null' Value in JavaScript
What's "This" in JavaScript Onclick
Efficient Way to Insert a Number into a Sorted Array of Numbers
JavaScript Time Zone Is Wrong for Past Daylight Saving Time Transition Rules
Using Underscore's "Difference" Method on Arrays of Objects
How to Calculate How Many Seconds Between Two Dates
Check If File Exists But Prevent 404 Error in Console from Showing Up