在Angular 6中,可以通过使用路由器(Router)和路由事件(Router events)来创建动态面包屑。以下是一种常见的实现方法:
@angular/router
模块。data
属性,用于存储面包屑相关的信息。例如:const routes: Routes = [
{ path: 'home', component: HomeComponent, data: { breadcrumb: 'Home' } },
{ path: 'products', component: ProductsComponent, data: { breadcrumb: 'Products' } },
{ path: 'products/:id', component: ProductDetailComponent, data: { breadcrumb: 'Product Detail' } },
// 其他路由配置...
];
ActivatedRoute
服务来获取当前路由的信息。例如,在你的面包屑组件中:import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-breadcrumb',
templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.css']
})
export class BreadcrumbComponent implements OnInit {
breadcrumbs: any[];
constructor(private router: Router, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(() => {
this.breadcrumbs = this.buildBreadcrumbs(this.activatedRoute.root);
});
}
buildBreadcrumbs(route: ActivatedRoute, url: string = '', breadcrumbs: any[] = []): any[] {
const label = route.routeConfig && route.routeConfig.data ? route.routeConfig.data.breadcrumb : '';
const path = route.routeConfig ? route.routeConfig.path : '';
const nextUrl = `${url}${path}/`;
const breadcrumb = {
label: label,
url: nextUrl
};
const newBreadcrumbs = [...breadcrumbs, breadcrumb];
if (route.firstChild) {
return this.buildBreadcrumbs(route.firstChild, nextUrl, newBreadcrumbs);
}
return newBreadcrumbs;
}
}
ngFor
指令来循环渲染面包屑导航。例如:<ol class="breadcrumb">
<li *ngFor="let breadcrumb of breadcrumbs; let last = last" [ngClass]="{ 'active': last }">
<a *ngIf="!last" [routerLink]="breadcrumb.url">{{ breadcrumb.label }}</a>
<span *ngIf="last">{{ breadcrumb.label }}</span>
</li>
</ol>
这样,当你在应用中导航到不同的路由时,面包屑组件会根据路由配置中定义的面包屑信息动态生成面包屑导航。
请注意,以上示例中的代码仅为演示目的,并未考虑完整的错误处理和边界情况。在实际应用中,你可能需要根据自己的需求进行适当的修改和扩展。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云负载均衡(CLB)。你可以通过以下链接了解更多信息:
领取专属 10元无门槛券
手把手带您无忧上云