Skip to content

Instantly share code, notes, and snippets.

@Muzammil-Bilwani
Last active November 8, 2018 08:58
Show Gist options
  • Save Muzammil-Bilwani/103f9790bb5e82243b427694a13323be to your computer and use it in GitHub Desktop.
Save Muzammil-Bilwani/103f9790bb5e82243b427694a13323be to your computer and use it in GitHub Desktop.
Breadcrumbs for Angular
ngOnInit() {
this.breadcrumbs$ = this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
distinctUntilChanged(),
map(event => {
return this.buildBreadCrumb(this.activatedRoute.root)
})
);
//Build your breadcrumb starting with the root route of your current activated route
this.menuService.alterMenu(menuItems);
}
buildBreadCrumb(route: ActivatedRoute,
url: string = '',
breadcrumbs = []
) {
const ROUTE_DATA_BREADCRUMB = 'breadcrumb';
const children: ActivatedRoute[] = route.children;
let label = '';
if (children.length === 0) {
return breadcrumbs;
}
for (const child of children) {
if (child.outlet !== PRIMARY_OUTLET) {
continue;
}
if (!child.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) {
return this.buildBreadCrumb(child, url, breadcrumbs);
}
if (
child.snapshot.url.map(segment => segment.path).length === 0
) {
return this.buildBreadCrumb(child, url, breadcrumbs);
}
const routeArray = child.snapshot.url.map(segment => segment.path);
for (let i = 0; i < routeArray.length; i++) {
label = child.snapshot.data[ROUTE_DATA_BREADCRUMB];
const routeURL = routeArray[i];
url += `/${routeURL}`;
const breadcrumb: BreadCrumb = {
label: label,
params: child.snapshot.params,
url: url
};
breadcrumbs.push(breadcrumb);
}
return this.buildBreadCrumb(child, url, breadcrumbs);
}
return breadcrumbs;
}
private isParam(params: Params, segment: string) {
for (const key of Object.keys(params)) {
const value = params[key];
if (value === segment) {
return true;
}
}
return false;
}
interface BreadCrumb {
label: string;
params?: Params;
url: string;
}
<ol class="breadcrumb">
<li *ngFor="let breadcrumb of breadcrumbs$ | async ;last as isLast" class="breadcrumb-item">
<a *ngIf="breadcrumb !== ''" [ngClass]="{black: isLast}" [routerLink]="[breadcrumb.url]">
{{ breadcrumb.label }}
</a>
<mat-icon *ngIf="!isLast">
chevron_right
</mat-icon>
</li>
</ol>
const routes: Routes = [{
path: '',
component: MainComponent,
data: {
breadcrumb: ''
},
children: [
{
path: "orders", component: ordersComponent,
data: {
breadcrumb: 'Order List'
},
children:
[
{
path: "", component: OrderListComponent
},
{
path: ":id", component: SingleOrderComponent, data: {
breadcrumb: 'Order Detail'
}
}
]
},
{
path: 'dashboard', component: OrderList
},
{ path: "", redirectTo: "orders", pathMatch: "full" },
]
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment