Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create breadcrumb when navigating nested components (Angular 2)

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
like image 425
Matt Avatar asked Dec 06 '22 18:12

Matt


2 Answers

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

like image 181
Artem Pogorelov Avatar answered Dec 09 '22 13:12

Artem Pogorelov


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);
  }
}
like image 25
Shenbo Avatar answered Dec 09 '22 15:12

Shenbo