import { Component, OnInit, ViewEncapsulation, Input } from '@angular/core'; import { ActivatedRoute, NavigationEnd, Router, Event } from '@angular/router'; import { distinctUntilChanged, filter, map, startWith } from 'rxjs/operators'; import { Observable } from 'rxjs'; interface BreadcrumbInterface { label: string; url: string; }; @Component({ selector: 'ta-ng-breadcrumb', templateUrl: './ng-breadcrumb.component.html', styleUrls: ['./ng-breadcrumb.component.scss'], }) export class NgBreadcrumbComponent { @Input() public baseRoute: string = 'Home'; public breadcrumbs$: Observable = this.router.events.pipe( filter((event: Event) => event instanceof NavigationEnd), distinctUntilChanged(), map((event: Event) => this.buildBreadCrumb(this.activatedRoute.root)), startWith(this.buildBreadCrumb(this.activatedRoute.root)), ); // Build your breadcrumb starting with the root route of your current activated route constructor( private activatedRoute: ActivatedRoute, private router: Router, ) {} public buildBreadCrumb( route: ActivatedRoute, url: string = '', breadcrumbs: BreadcrumbInterface[] = [], ): BreadcrumbInterface[] { // If no routeConfig is avalailable we are on the root path const label: any = route.routeConfig ? route.routeConfig.data['breadcrumb'] : this.baseRoute; const path: string = route.routeConfig ? route.routeConfig.path : ''; // In the routeConfig the complete path is not available, // so we rebuild it each time const nextUrl: string = `${url}${path}/`; const breadcrumb: BreadcrumbInterface = { label, url: nextUrl, }; const newBreadcrumbs: BreadcrumbInterface[] = [...breadcrumbs, breadcrumb]; 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; } }