Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
822 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...