|
import { Component, OnInit } from '@angular/core'; |
|
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; |
|
import { IBreadcrumb } from './breadcrumb.interfaces'; |
|
|
|
import { filter, distinctUntilChanged } from 'rxjs/operators'; |
|
|
|
@Component({ |
|
selector: 'app-breadcrumb', |
|
templateUrl: './breadcrumb.component.html', |
|
styleUrls: ['./breadcrumb.component.css'] |
|
}) |
|
export class BreadcrumbComponent implements OnInit { |
|
public breadcrumbs: Array<IBreadcrumb>; |
|
|
|
constructor(private router: Router, private activatedRoute: ActivatedRoute, private route: Router) { |
|
this.breadcrumbs = this.buildBreadCrumb(this.activatedRoute.root); |
|
} |
|
|
|
ngOnInit() { |
|
this.router.events.pipe( |
|
filter((event) => event instanceof NavigationEnd), |
|
distinctUntilChanged(), |
|
).subscribe(() => { |
|
this.breadcrumbs = this.buildBreadCrumb(this.activatedRoute.root); |
|
if (this.route.url != "/") { |
|
this.breadcrumbs.unshift({ |
|
label: "Home", |
|
url: "", |
|
icon: "home", |
|
image: "", |
|
isClickable: true |
|
}) |
|
} |
|
|
|
}) |
|
} |
|
|
|
/** |
|
* Recursively build breadcrumb according to activated route. |
|
* @param route |
|
* @param url |
|
* @param breadcrumbs |
|
*/ |
|
buildBreadCrumb(route: ActivatedRoute, url: string = '', breadcrumbs: IBreadcrumb[] = []): IBreadcrumb[] { |
|
//If no routeConfig is avalailable we are on the root path |
|
let configData = route.routeConfig?.data; |
|
let label = configData && configData.breadcrumb ? configData.breadcrumb : ""; |
|
let icon = configData && configData.icon ? configData.icon : ''; |
|
let image = configData && configData.image ? configData.image : false; |
|
let isClickable = configData && configData.isClickable !== undefined ? configData.isClickable : true; |
|
|
|
let path = configData && configData.path ? configData.path : ""; |
|
|
|
// If the route is dynamic route such as ':id', remove it |
|
const lastRoutePart = path.split('/').pop(); |
|
const isDynamicRoute = lastRoutePart.startsWith(':'); |
|
if (isDynamicRoute && !!route.snapshot) { |
|
const paramName = lastRoutePart.split(':')[1]; |
|
path = path.replace(lastRoutePart, route.snapshot.params[paramName]); |
|
label = route.snapshot.params[paramName]; |
|
} |
|
|
|
//In the routeConfig the complete path is not available, |
|
//so we rebuild it each time |
|
const nextUrl = path ? `${url}/${path}` : url; |
|
|
|
const breadcrumb: IBreadcrumb = { |
|
label: label, |
|
url: nextUrl, |
|
icon: icon, |
|
image: image, |
|
isClickable: isClickable, |
|
}; |
|
// Only adding route with non-empty label |
|
const newBreadcrumbs = breadcrumb.label ? [...breadcrumbs, breadcrumb] : [...breadcrumbs]; |
|
if (route.firstChild) { |
|
//If we are not on our current path yet, |
|
//there will be more children to look after, to build our breadcumb |
|
return this.buildBreadCrumb(route.firstChild, nextUrl, newBreadcrumbs); |
|
} |
|
return newBreadcrumbs; |
|
} |
|
} |