How to implement breadcrumb in Angular 7
Update the router subscribe logic in Breadcrumb component ts file with below code.
ngOnInit() {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.pipe(map(() => this.activatedRoute))
.pipe(map((route) => {
while (route.firstChild) { route = route.firstChild; }
return route;
}))
.pipe(filter(route => route.outlet === PRIMARY_OUTLET))
.subscribe(route => {
let snapshot = this.router.routerState.snapshot;
this.breadcrumbs = [];
let url = snapshot.url;
let routeData = route.snapshot.data;
console.log(routeData);
let label = routeData['breadcrumb'];
let params = snapshot.root.params;
this.breadcrumbs.push({
url: url,
label: label,
params: params
});
});
}
Working stackblitz Link: https://stackblitz.com/edit/breadcrumb-in-angular-7
Recently I have implemented ng-dynamic-breadcrumb, ng7-dynamic-breadcrumb, ng7-bootstrap-breadcrumb and ng7-mat-breadcrumb Angular breadcrumb Modules. Please check the these modules, I hope this will help for dynamic breadcrumbs.
Amit Dube
Seasoned Technical Professional offering 14+ years of rich and versatile experience in Software design, architecture, and development. A result-oriented, forward-thinking, and committed individual with a passion for technology.
Updated on June 28, 2020Comments
-
Amit Dube almost 4 years
I am trying to implement breadcrumbs in Angular 7 based Application.
HTML Template for root component containing breadcrumb component is mentioned below (breadcrumb is outside router outlet)
<app-layout> <div> <app-breadcrumb></app-breadcrumb> <router-outlet></router-outlet> </div> </app-layout>
Breadcrumb component ts file
ngOnInit() { this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((router) => { let snapshot = this.router.routerState.snapshot; this.breadcrumbs = []; let url = snapshot.url; let routeData: Data = snapshot.root.data; let label = routeData['breadcrumb']; let params = snapshot.root.params; this.breadcrumbs.push({ url: url, label: label, params: params }); });
Breadcrumb component html file
<nav aria-label='breadcrumb'> <ol class='breadcrumb'> <li *ngFor='let breadcrumb of breadcrumbs'> <a [routerLink]='[breadcrumb.url, breadcrumb.params]' routerLinkActive='active'>{{ breadcrumb.label }}</a> </li> </ol> </nav>
Route definition is as follows
const routes: Routes = [ { path: 'folders', component: FolderManagementComponent, data: { breadcrumb: 'Home' } }, { path: 'folders/list-documents', component: ListDocumentsComponent, data: { breadcrumb: 'Documents' } }, { path: '', redirectTo: '/folders', pathMatch: 'full', data: { breadcrumb: 'Home' }} ];
But I am not getting data and params