I am using angular2 router.
To draw the breadcrumb of an url, lets say site.com/a/b/c/15 I do the following:
site.com/a/b/c/15
Updated for RC5
Instead of starting with the current URL and trying to get the routes from the URL, you can get all of the activated routes (associated with the primary outlet) from the RouterState
:
After the end of each successful navigation lifecycle, the router builds a tree of
ActivatedRoute
s, which make up the current state of the router. We can access the currentRouterState
from anywhere in our application using theRouter
service and therouterState
property.The router state provides us with methods to traverse up and down the route tree from any activated route to get information we may need from parent, child and sibling routes. -- reference
Subscribe to router events, then, after each NavigationEnd
event, walk down the tree of ActivatedRoute
s from the root
:
import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';
@Component({
selector: 'breadcrumbs',
template: `
<div>
breadcrumbs:
<span *ngFor="let breadcrumb of breadcrumbs; let last = last">
<a [routerLink]="breadcrumb.url">{{breadcrumb.label}}</a>
<span *ngIf="!last">></span>
</span>
</div>`
})
export class BreadcrumbsComponent {
breadcrumbs: Array<Object>;
constructor(private router:Router, private route:ActivatedRoute) {}
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => { // note, we don't use event
this.breadcrumbs = [];
let currentRoute = this.route.root,
url = '';
do {
let childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if(route.outlet === 'primary') {
let routeSnapshot = route.snapshot;
console.log('snapshot:', routeSnapshot)
url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
this.breadcrumbs.push({
label: route.snapshot.data.breadcrumb,
url: url });
currentRoute = route;
}
})
} while(currentRoute);
})
}
}
Routes look like this:
{ path: '', component: HomeComponent, data: {breadcrumb: 'home'}}
Plunker - RC.5, router 3.0.0-rc.1
See also https://stackoverflow.com/a/38310404/215945 for a similar solution.
Any breadcrumb solution has to handle -
I have created an Angular library to handle all these, called xng-breadcrumbs - https://github.com/udayvunnam/xng-breadcrumb
feel free to check, An Angular app developed showing the breadcrumbs usage - https://xng-breadcrumb.netlify.com
Angular library planning, creation, and continuous release is well documented in this medium article
So far, the most feasable solution is (done):
Pros: works
Cons: redoing url-route recognition manuall without using the ng2 router one