4

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
Matt
  • 609
  • 2
  • 12
  • 19

5 Answers5

9

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

  • 1
    Very nice. Note that you can get the `root` of the UrlTree from `Router.routerState.root`, rather than from private variable `_root`. This also allows you to use NavigationEnd rather than RoutesRecognized. See [this answer](http://stackoverflow.com/a/38808735/215945) for more info and an RC.4 plunker. – Mark Rajcok Aug 09 '16 at 03:02
  • I also ran into an issue with this, did some digging and came up with a very similar implementation in RC5 and the new component router. https://github.com/mikelunn/angular2-breadcrumb – Mike Lunn Sep 09 '16 at 13:30
6

Adding on NullԀʇɹ's answer, you can create a breadcrumb dynamically by using PrimeNG's breadcrumb.

You'll firstly need a BreadcrumbService:

import { EventEmitter, Injectable } from '@angular/core';

import { MenuModule, MenuItem } from 'primeng/primeng';

/**
 * A service provides functions to get and set the breadcrumb of the app
 */
@Injectable()
export class BreadcrumbService {
  items: MenuItem[] = [];

  public breadcrumbChanged: EventEmitter<MenuItem[]> = new EventEmitter<MenuItem[]>();

  getBreadcrumb(): MenuItem[] {
    return this.items;
  }

  setBreadcrumb(breadcrumb: MenuItem[]): void {
    this.items = breadcrumb;
    this.breadcrumbChanged.next(this.items);
  }

}

Then in your main component, say AppComponent, inject your BreadCrumbService, and tells it whenever breadcrumb changes, update it:

import { BreadcrumbService } from './breadcrumb.service';
import { BreadcrumbModule, MenuItem } from 'primeng/primeng';

@Component({
  selector: 'my-app',
  templateUrl: '/app.component.html',
})
export class AppComponent {
  breadcrumb: MenuItem[];

  constructor(private breadcrumbService: BreadcrumbService) {
    // whenever breadcrumb changes, update it
    this.breadcrumbService.breadcrumbChanged.subscribe(breadcrumb => { this.breadcrumb = breadcrumb });
  }
}

And your corresponding html for your AppComponent should look like:

<p-breadcrumb [model]="breadcrumb"></p-breadcrumb>

Now in the component you want to dynamically create a breadcrumb for, say My-Product:

import { OnInit } from "@angular/core";
import { BreadcrumbService } from '../../common/breadcrumb.service'; 
import { MenuModule, MenuItem } from 'primeng/primeng';

@Component({
  selector: 'my-product.component',
  templateUrl: './my-product.component.html',
})
export class MyProduct implements OnInit {
  breadcrumbItems: MenuItem[] = [];

  constructor(private breadcrumb: BreadcrumbService) {}

  ngOnInit() {
    this.breadcrumbItems.push({label:'Products'});
    this.breadcrumbItems.push({label:'Category-C', routerLink: ['/products/category-c']});
    this.breadcrumbItems.push({label: 'My-Product'});
    this.breadcrumb.setBreadcrumb(this.breadcrumbItems);
  }
}
Shenbo
  • 226
  • 4
  • 11
1

Using bootflat Theme i have created my own Breadcrumb for angular2 project. This Breadcrumb also support Routing in angular2. you just have to use these predefined components given here in the repo.

https://github.com/MrPardeep/Angular2-DatePicker

here is the code for using Breadcrum in HTML file:

<breadcrumb>
    <tab name="Home" icon="glyphicon glyphicon-home"></tab>
    <a [routerLink]="['/Components']">
        <tab name="Cutom Angular 2 Components" icon="glyphicon glyphicon-home"></tab>
    </a>
    <tab action="active" name="Datepicker" icon="glyphicon glyphicon-list-alt"></tab>
</breadcrumb>

hope this may help you and will useful for others too.

here is Demo for the Breadcrumb.

enter image description here

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

PrimeNG has an Angular2 breadcrumb component. The demo is: http://www.primefaces.org/primeng/#/breadcrumb

The product is still in beta and I haven't tried using this component yet, but it may suite your needs.

Heather92065
  • 7,333
  • 6
  • 31
  • 39
  • Thank you NullPtr92065, this example is cool, but in that case is hand code the breadcrumb. I am looking something that observe routing, when exist a new route update it automatically. – Matt May 27 '16 at 00:50
0

I think xng-breadcrumb handles your use-case along with few other well-thought use cases

  • Default routing with support for nested routing
  • The declarative approach of defining breadcrumbs in routing config
  • Dynamic asynchronous way to update any route's breadcrumb
  • way to skip specific routes from displaying in breadcrumbs

you can check - https://github.com/udayvunnam/xng-breadcrumb

Demo app showing the breadcrumbs usage - https://xng-breadcrumb.netlify.com

Uday Vunnam
  • 337
  • 2
  • 5