问题
Is there a way to implement navigation history based breadcrumb instead of normal route path based breadcrumb.
example Route : Home - HChild1 - HChild1.1 Home - HChild2 - HChild2.1
If user navigates to HChild2.1 from Home page breadcrumb should be Home | HChild2.1
instead of Home | HChild2 | HChild2.1
Then if user navigates to HChild1.1 from HChild2.1 then breadcrumb should be Home | HChild2.1 | HChild1.1
instead of Home | HChild1.1 | HChild1.1
what I have is normal route path based breadcrumb which doesn't serve my purpose as I can only navigate to the paranet component but not to the previous component.
Thanks
回答1:
Use breadcrumb component to populate last route in navigation end route.
route must have breadcrumb data
//Home route
{
path: '',
component: HomeComponent,
data: {breadcrumb:'Home'},
}
Here is the breadcrumb component I made.
export interface BreadCrumb {
label: string;
url: string;
};
@Component({
selector: 'breadcrumb',
template: `<span *ngFor="let breadcrumb of breadcrumbs" >
<a [routerLink]="breadcrumb.url">
{{ breadcrumb.label }}
</a>|
</span>`
})
export class BreadCrumbComponent {
private history = [];
breadcrumbs: BreadCrumb[] = [];
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
) { }
public ngOnInit(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd), distinctUntilChanged(),map(() => {
return this.buildBreadCrumb(this.activatedRoute.root)
}
))
.subscribe(event => {
this.breadcrumbs.push(event);
console.log(this.breadcrumbs)
});
}
buildBreadCrumb(route: ActivatedRoute, url: string = ''): BreadCrumb {
const label = route.routeConfig ? route.routeConfig.data['breadcrumb'] : 'Home';
const path = route.routeConfig ? `/${route.routeConfig.path}` : '';
const nextUrl = `${url}${path}`;
const breadcrumb = {
label: label,
url: nextUrl
};
if (route.firstChild) {
return this.buildBreadCrumb(route.firstChild, nextUrl);
}
return breadcrumb;
}
}
来源:https://stackoverflow.com/questions/56697897/angular-breadcrumb-based-on-navigation-history-instead-of-route-path