While writing these lines, the selected answer does not seem to work anymore.
If you want to be notified when a route change, you can subscribe to the Router.events
observable. for example, NavigationEnd
events store the url as a property:
this.router.events.filter(evt => evt instanceof NavigationEnd)
.map(evt =>evt.url)
.subscribe(url=>console.log(url));
If you want to compare the current route to a child path -let's say "child"
-. You can use the Router.isActive()
method:
let events = this.router.events;
events.filter(evt => evt instanceof NavigationEnd)
.map(() =>{
let exact=true;
let childRoute=this.router.createUrlTree(["child"], {relativeTo: this.route}
return this.router.isActive(childRoute,exact);
})
.subscribe(active=>console.log(`child route is active :${active`));
Notes:
this.router
is a Router
instance
this.route
is an instance of ActivatedRoute
exact
is used to make exact match : if the route was "child/grand-child"
this.router.isActive(route,true)
would return false
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…