LearnToday
LearnToday

Reputation: 2902

How to get the active route in app.component

I want to get the active route in app.component so I can hide some elements in my app header.

For instance, if route /assets,

I set the isHeader: boolean = true;

I get an object when I do this:

import {Router, ActivatedRoute} from '@angular/router';

 constructor(router: ActivatedRoute) {
   this.route = router.url;
   console.log(this.route);
}

How can I get the route value /assets?

Upvotes: 1

Views: 4090

Answers (1)

slaesh
slaesh

Reputation: 16917

You have to "listen" to the router-events.

See my plunker for a working demo: https://plnkr.co/edit/XJmOa7rmtvBpuJDfQ2Vd?p=preview

The interesting part is this code snippet:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <a routerLink="/cmp1">cmp1</a><br />
    <a routerLink="/cmp2">cmp2</a><br />
    <a routerLink="/cmp3">cmp3</a><br />

    <router-outlet></router-outlet>
  `,
})
export class App {
  name:string;
  constructor(private _r: Router) {
    this.name = 'Angular2'

    this._r.events.subscribe(event => {
      if (event instanceof RoutesRecognized) {
        console.log('navigated to:', event.url);
        console.log('route state', event.state);
        console.log('');
      }
      else if (event instanceof NavigationEnd) {
        // if u dont need the state, you could even use this event-type..
      }
    });
  }
}

Subscribe to the router-events and check which type of event was fired. If you want to use the state (params, queryParams, ...) i recommend to use RoutesRecognized-event-type. but you can even use NavigationEnd-event-type if you only want to get the current url..

Upvotes: 4

Related Questions