Skip to content

Instantly share code, notes, and snippets.

@jrmlstf
Created January 18, 2018 15:53
Show Gist options
  • Save jrmlstf/39750b1aa1ea6af80c6b3eecff5b60f2 to your computer and use it in GitHub Desktop.
Save jrmlstf/39750b1aa1ea6af80c6b3eecff5b60f2 to your computer and use it in GitHub Desktop.
import { Component } from '@angular/core';
import { ActivatedRouteSnapshot, NavigationEnd, Params, PRIMARY_OUTLET, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
interface BreadcrumbItem {
label: string;
params?: Params;
url: string;
}
@Component({
selector: 'app-breadcrumb',
templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.scss']
})
export class BreadcrumbComponent {
public breadcrumbs: BreadcrumbItem[];
private readonly ROUTE_DATA_BREADCRUMB = 'breadcrumb';
constructor(private router: Router) {
this.breadcrumbs = [];
this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(() => {
const root: ActivatedRouteSnapshot = this.router.routerState.snapshot.root;
this.breadcrumbs = this.getBreadcrumbs(root);
});
}
private getBreadcrumbs(route: ActivatedRouteSnapshot, url: string = '', breadcrumbs: BreadcrumbItem[] = []): BreadcrumbItem[] {
if (route.outlet !== PRIMARY_OUTLET) {
return;
}
url += `/${route.url.map(segment => segment.path).join('/')}`;
const label = route.data[this.ROUTE_DATA_BREADCRUMB];
if (label && label !== route.parent.data[this.ROUTE_DATA_BREADCRUMB]) {
breadcrumbs.push({
label: label,
params: route.params,
url: url
});
}
if (route.children) {
for (const child of route.children) {
this.getBreadcrumbs(child, url, breadcrumbs);
}
}
return breadcrumbs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment