3

I am trying to check the active child route in a parent component, but I am having difficulties with it.

I have tried to subscribe to the ActivatedRoute by doing something like this:

class ParentComponent {
    constructor(private _route:ActivatedRoute) {}

    ngOnInit() {
        this._route.data.subscribe(value => console.log(value)});
    }
}

I have read a lot of threads on Stack Overflow, but can't find a solution that checks and gets updated regarding the child routes of a parent component.

Any ideas?

2 Answers2

4

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
n00dl3
  • 21,213
  • 7
  • 66
  • 76
  • Getting this error .. `property 'url' does not exist on type 'Event' property 'url' does not exist on type 'RouteConfigLoadStart'` – Aakriti.G Jan 02 '18 at 10:05
  • @Aakriti You need to filter router events and only take `NavigationEnd` events. `this.router.events.filter(evt => evt instanceof NavigationEnd)` (may be you need to assert type to be `Observable` like this : `this.router.events.filter(evt => evt instanceof NavigationEnd) as Observable` – n00dl3 Jan 02 '18 at 10:22
  • How will we use map with this .. it is saying `cannot find name map` – Aakriti.G Jan 02 '18 at 10:40
2

You can access active child route using below code snippet

constructor(private router:Router, private currentActivatedRoute:ActivatedRoute)
// this should be called in ngOnInit
    var state = this.router.routerState
    var children = state.children(this.currentActivatedRoute)

RouterState, Tree

Arpit Agarwal
  • 3,993
  • 24
  • 30
  • 1
    `Property 'children' does not exist on type 'RouterState'` ... :/ – Inigo Nov 21 '16 at 17:31
  • 3
    Not sure if something changed since this answer was posted, but children is a property of ActivatedRoute, NOT Router – Inigo Nov 21 '16 at 17:41