Angular2 (rc4) - Check active child route in paren

2019-01-26 21:17发布

问题:

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?

回答1:

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



回答2:

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