8

I have a route with route children like this:

{
    path: 'dashboard',
    children: [{
        path: '',
        canActivate: [CanActivateAuthGuard],
        component: DashboardComponent
    }, {
        path: 'wage-types',
        component: WageTypesComponent
    }]
}

And in the browser I want to get the activated parent route like

host.com/dashboard/wage-types

How to get the /dashboard but possible with Angular 2 and not in JavaScript, but also I can accept JavaScript code too but primary Angular 2.

Narendra Jadhav
  • 9,619
  • 15
  • 29
  • 41

2 Answers2

21

You can do this by using the parent property on the ActivatedRoute - something like this.

export class MyComponent implement OnInit {

    constructor(private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.activatedRoute.parent.url.subscribe((urlPath) => {
            const url = urlPath[urlPath.length - 1].path;
        })
    }

}

You can see everything from the ActivatedRoute in more detail here: https://angular.io/api/router/ActivatedRoute

Francesco Borzi
  • 48,083
  • 42
  • 155
  • 225
peppermcknight
  • 1,455
  • 16
  • 29
  • 2
    yes, but this gives me an array, how can i filter to get only the /dashboard ? –  Feb 27 '17 at 11:07
  • because you are using the parent of the current activated route, the last item in the array of UrlSegments will be the parent url - updated my answer to show this and to reflect my mistake the the url property is actually an observable – peppermcknight Feb 27 '17 at 11:22
2

You can check for parent route by determining if only one slash is present in it:

 constructor(private router: Router) {}

 ngOnInit() {
      this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((x: any) => {
          if (this.isParentComponentRoute(x.url)) {
            // logic if parent main/parent route
          }
        });
  }

 isParentComponentRoute(url: string): boolean {
    return (
      url
        .split('')
        .reduce((acc: number, curr: string) => (curr.indexOf('/') > -1 ? acc + 1 : acc), 0) === 1
    );
  }
Eugen Sunic
  • 12,218
  • 8
  • 60
  • 78