Jason Goemaat
Jason Goemaat

Reputation: 29234

Know in parent what child RouteSegment is selected?

I would like to be able to find out in a parent component, or the app component, which child route is active. For instance to be able to style the active route link. I see that [routeLink] adds the 'router-link-active' class, but in my example I have a 'home' with route '/' that always has that class no matter what route I use. Is there any way to see in the parent of the outlet what route you are on?

I've injected Location from @angular/common and am able to see the full path I guess from looking at this when the route changes:

ngOnInit() {
  this.router.changes.subscribe(changes => {
    console.log('location info:', this.location.platformStrategy.path());
  });
}

Is there a way to get at the RouteTree or the currently active RouteSegment from the parent? Or to check the router-outlet and see what component is loaded into it?

Upvotes: 2

Views: 353

Answers (2)

Jason Goemaat
Jason Goemaat

Reputation: 29234

After the answer from @Gunter this is how I ended up doing it:

constructor(
  public router: Router,
  public routerSerializer: RouterUrlSerializer,
  public location: Location
) { }

ngOnInit() {
  this.router.changes.subscribe(changes => {
    this.updatePath();
  });
}

updatePath() {
  let path = this.location.path();
  let urlTree = this.routerSerializer.parse(path);
  let node = urlTree;
  let segment: UrlSegment = urlTree.root;
  let result = segment.segment;
  while (urlTree.children(segment).length > 0) {
    segment = urlTree.children(segment)[0];
    if (result.length > 1) result += '/';
    result += segment.segment; // is a string
  }

  this.path = result;
}

children() takes a UrlSegment and returns an array of UrlSegment. The root segment.segment is an empty string, I could do this if I wanted to make it '/':

this.path = result.length == 0 ? "/" : result;

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657937

You can access the current route like

  constructor(private router:Router, private routeSerializer:RouterUrlSerializer, private location:Location) {
    router.changes.first().subscribe(() => {

      console.log('router', this.router);
      let urlTree = this.routeSerializer.parse(location.path());

      // to get the individual segments of the route use
      console.log('serializer', urlTree.children(urlTree.root)[0].segment);
      console.log('serializer', urlTree.children(urlTree.children(urlTree.root)[0])[0].segment);
    });
  }

Upvotes: 2

Related Questions