html:
<nz-breadcrumb class="app-breadcrumb" nzSeparator="/">
<!-- <nz-breadcrumb-item>首页</nz-breadcrumb-item>-->
<nz-breadcrumb-item *ngFor="let breadcrumb of breadcrumbs">
<a [routerLink]="[breadcrumb.url, breadcrumb.params]">{{ breadcrumb.label }}</a>
</nz-breadcrumb-item>
</nz-breadcrumb>
css
.app-breadcrumb {
padding: 0 12px;
line-height: 32px;
background: #fff;
}
ts
import {filter} from 'rxjs/operators';
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router, Params, NavigationEnd, PRIMARY_OUTLET} from '@angular/router';
import { BreadcrumbOption } from 'ng-zorro-antd';
interface IBreadcrumb {
label: string;
params: Params;
url: string;
}
@Component({
selector: 'app-breadcrumb',
templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.scss'],
})
export class BreadcrumbComponent implements OnInit {
public breadcrumbs: IBreadcrumb[];
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
this.breadcrumbs = [];
}
ngOnInit(): void {
this.router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe((event) => {
// 设置面包屑
const root: ActivatedRoute = this.activatedRoute.root;
this.breadcrumbs = this.getBreadcrumbs(root);
});
}
/**
* 返回表示面包屑的IBreadcrumb对象的数组
*/
private getBreadcrumbs(route: ActivatedRoute, url: string = '', breadcrumbs: IBreadcrumb[] = []): IBreadcrumb[] {
const ROUTE_DATA_BREADCRUMB = 'breadcrumb';
const children: ActivatedRoute[] = route.children;
// If there's no sub root, then stop the recurse and returns the generated breadcrumbs.
if (children.length === 0) {
return breadcrumbs;
}
for (const child of children) {
if (child.outlet === PRIMARY_OUTLET) {
// Only parse components in primary router-outlet (in another word, router-outlet without a specific name).
// Parse this layer and generate a breadcrumb item.
const routeURL: string = child.snapshot.url
.map((segment) => segment.path)
.filter((path) => path)
.join('/');
const nextUrl = url + `/${routeURL}`;
const breadcrumbLabel = child.snapshot.data[ROUTE_DATA_BREADCRUMB];
// If have data, go to generate a breadcrumb for it.
if (routeURL && breadcrumbLabel) {
const breadcrumb: BreadcrumbOption = {
label: breadcrumbLabel,
params: child.snapshot.params,
url: nextUrl.replace('//', '/'),
};
breadcrumbs.push(breadcrumb);
}
return this.getBreadcrumbs(child, nextUrl, breadcrumbs);
}
}
return undefined;
}
}