Create breadcrumb when navigating nested components (Angular 2)

Matt picture Matt · May 26, 2016 · Viewed 14.5k times · Source

I am struggling with this :)

The idea is to have a component and when navigate trough sub-views update the breadcrumb for example:

<breadcrumb> Products / Category-C / My-Product </breadcrumb>

Products -> Category-A
         -> Category-B
         -> Category-C  
                  |-> My-Product

Answer

Artem Pogorelov picture Artem Pogorelov · Jul 11, 2016

May be this is not the best solution but you can use RoutesRecognized router event and traverse through event.state._root childrens:

import {Injectable, EventEmitter} from '@angular/core';
import {Router, RoutesRecognized, ActivatedRouteSnapshot} from '@angular/router';

@Injectable()
export class BreadcrumbComponent {
public breadcrumbs:Array<any>;
constructor(private _router:Router) {

this._router.events.subscribe(eventData => {
  if (eventData instanceof RoutesRecognized) {
    let event:any = eventData;
    let currentUrlPart = event.state._root;
    let currUrl = '#'; //for HashLocationStrategy

    this.breadcrumbs = [];
    while (currentUrlPart.children.length > 0) {
      currentUrlPart = currentUrlPart.children[0];
      let routeSnaphot = <ActivatedRouteSnapshot>currentUrlPart.value;

      currUrl += '/' + routeSnaphot.url.map(function (item) {
          return item.path;
        }).join('/');

      this.breadcrumbs.push({
        displayName: (<any>routeSnaphot.data).displayName,
        url: currUrl,
        params: routeSnaphot.params
      })
       console.log(this.breadcrumbs)
    }               
  }
});
}}

And route config looks like this:

export const AppRoutes:RouterConfig = [{
path: 'app',
component: App,
data: {
  displayName: 'Home'
},
children: [
  {

    data: {
      displayName: 'Pages'
    },
    path: 'pages',
    component: Pages,       
    children: [             
    ]
  }
]}]

Tested with Angular 2 RC4, @angular/router 3.0.0-beta.1