Angular Breadcrumb based on navigation history instead of route path

故事扮演 提交于 2020-05-16 01:23:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!