Angular2 (rc4) - Check active child route in parent component

前端 未结 2 1245
长情又很酷
长情又很酷 2020-12-11 10:21

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 som

相关标签:
2条回答
  • 2020-12-11 10:48

    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
    0 讨论(0)
  • 2020-12-11 10:49

    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

    0 讨论(0)
提交回复
热议问题