您可以使用events
of执行此操作Router module
,然后创建一个名为breadcrumb
显示导航的组件
最终结果如下:
面包屑.component.ts:
import { Component, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, UrlSegment, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-breadcrumb',
encapsulation: ViewEncapsulation.None,
templateUrl: './breadcrumb.component.html'
})
export class BreadcrumbComponent {
public pageTitle: string;
public breadcrumbs: { name: string; url: string }[] = [];
constructor(
public router: Router,
public activatedRoute: ActivatedRoute) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.breadcrumbs = [];
this.parseRoute(this.router.routerState.snapshot.root);
}
})
}
parseRoute(node: ActivatedRouteSnapshot) {
if (node.data['breadcrumb']) {
if (node.url.length) {
let urlSegments: UrlSegment[] = [];
node.pathFromRoot.forEach(routerState => {
urlSegments = urlSegments.concat(routerState.url);
});
const url = urlSegments.map(urlSegment => {
return urlSegment.path;
}).join('/');
this.breadcrumbs.push({
name: node.data['breadcrumb'],
url: '/' + url
})
}
}
if (node.firstChild) {
this.parseRoute(node.firstChild);
}
}
}
面包屑.component.html:
<ol class="breadcrumb" id="breadcrumb">
<li class="breadcrumb-item">>
<i class="fa fa-home mr-2"></i>Home</a>
</li>
<li *ngFor="let breadcrumb of breadcrumbs; let i = index;" class="breadcrumb-item">
<a [hidden]="i == (breadcrumbs.length - 1)">{{breadcrumb.name}}</a>
<span [hidden]="i != (breadcrumbs.length - 1)">
<b>{{breadcrumb.name}}</b>
</span>
</li>
</ol>
无论您在哪里定义路线,设置一个名为的数据breadcrumb
并分配特定名称,如下所示:
带模块:
{ path: 'incident', loadChildren:(...), data: { breadcrumb: 'Incident' } }
与组件:
{ path: "personal",component: (...), data: { breadcrumb: "Personal" } }
用法 :
在您的布局或母版页中放置以下内容app-breadcrumb
<app-breadcrumb></app-breadcrumb>