'Angular breadcrumb with lazy loading and nested routes
I am working with Angular@12 to build a breadcrumb and I would like to know how to incorporate lazy loading and nested routes with my breadcrumb.
I am creating the breadcrumb using a BreadcrumbService as follows:
constructor(private router: Router) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd)
)
.subscribe((event) => {
const root = this.router.routerState.snapshot.root;
const breadcrumbs: Breadcrumb[] = [{
label: 'Home',
url: '/',
}, ];
this.addBreadcrumb(root, [], breadcrumbs);
this._breadcrumbs$.next(breadcrumbs);
});
}
private addBreadcrumb(
route: ActivatedRouteSnapshot,
parentUrl: string[],
breadcrumbs: Breadcrumb[]
) {
if (route) {
const routeUrl = parentUrl.concat(route.url.map((url) => url.path));
if (route.data.title) {
const breadcrumb = {
label: this.getLabel(route.data),
url: '/' + routeUrl.join('/'),
};
breadcrumbs.push(breadcrumb);
}
this.addBreadcrumb(
route.firstChild as ActivatedRouteSnapshot,
routeUrl,
breadcrumbs
);
}
}
With the BreadcrumbService like this, I expect my route to be nested like follows:
const routes: Routes = [
{
path: '',
component: NewsPageComponent,
data: { title: 'news' },
children: [
{
path: ':newsId',
component: NewsDetailComponent,
data: { title: 'content' },
},
],
},
];
Setting the routes like above will make my breadcrumb display correctly, but the NewsDetailComponent will never get to show because Angular check the route from left to right and stop once there is a partial match.
- I want to know if it is possible to have a nested route while showing corresponding page content and the breadcrumb correctly.
- If not, how can I modify the route or the BreadcrumbService to achieve my desired result?
Thank you for the help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
