angular2 利用路由制作breadcrumb面包屑

本文档介绍了如何利用Angular2的路由功能制作breadcrumb面包屑导航。通过分析app.routing.module.ts的路由配置,展示了如何为IndexComponent、SigninComponent和SignupComponent设置面包屑路径。同时提到了AppComponent和BreadcrumbComponent的角色,后者在实现面包屑功能中起关键作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址 Angular2 Breadcrumb using Router

在web领域 面包屑依旧是ui导航的必备元素之一,我们将用angular的Router来制作一个breadcrumb面包屑

Demo

Check out my demo plunker: https://plnkr.co/edit/aNEoyZ?p=preview

Router

首先 让我们快速浏览一下app.routing.module.ts,看看我们的路由配置:

import { ModuleWithProviders } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { IndexComponent } from "./index/index.component";
import { RootComponent } from "./root/root.component";
import { SigninComponent } from "./signin/signin.component";
import { SignupComponent } from "./signup/signup.component";

const routes: Routes = [
  {
    path: "",
    component: RootComponent,
    children: [
      {
        path: "signin",
        component: SigninComponent,
        data: {
          breadcrumb: "Sign In"
        }
      },
      {
        path: "signup",
        component: SignupComponent,
        data: {
          breadcrumb: "Sign Up"
        }
      },
      {
        path: "",
        component: IndexComponent
      }
    ]
  },
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

在本应用中 根路由有三个子状态
/ - IndexComponent将出现在缺省页.
/signin - SigninComponent将展示一个登录form.
/signup - SignupComponent将展示一个注册form.
这三个路由被RootComponent包裹。/signin 和 the /signup 路由都有一个data 里面有bredcrumb属性
@NgModule 声明了所有的组件

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from "./app.component";
import { BreadcrumbComponent } from './breadcrumb/breadcrumb.component';
import { RootComponent } from "./root/root.component";
import { IndexComponent } from "./index/index.component";
import { SigninComponent } from "./signin/signin.component";
import { SignupComponent } from "./signup/signup.component";
import { routing } from "./app.routing.module";

@NgModule({
  imports: [
    BrowserModule,
    routing
  ],
  declarations: [
    AppComponent,
    BreadcrumbComponent,
    IndexComponent,
    RootComponent,
    SigninComponent,
    SignupComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Note that I have also defined a BreadcrumbComponent. We’ll get to that in a minute.
注意我还定义了一个BreadcrumbComponent,等等我们会说。

Also note that I have imported the exported the routing function from the app.routing.module.ts file.
还需要注意 我导入了app.routing.module.ts里面导出的routing函数。

AppComponent

下面我们来看AppComponent,它包含了 和 .

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Killer App</h1>
    <breadcrumb></breadcrumb>
    <router-outlet></router-outlet>
  `
})
export class AppComponent implements OnInit {
  constructor() {}
  ngOnInit() {}
}

是占位符 以后的内容就往这个位置放

breadcrumb.component.ts:

import { Component, OnInit } from "@angular/core";
import { Router, ActivatedRoute, NavigationEnd, Params, PRIMARY_OUTLET } from "@angular/router";
import "rxjs/add/operator/filter";

interface IBreadcrumb {
  label: string;
  params: Params;
  url: string;
}

@Component({
  selector: "breadcrumb",
  template: `
    <ol class="breadcrumb">
      <li><a routerLink="" class="breadcrumb">Home</a></li>
      <li *ngFor="let breadcrumb of breadcrumbs">
        <a [routerLink]="[breadcrumb.url, breadcrumb.params]">{{ breadcrumb.label }}</a>
      </li>
    </ol>
  `
})
export class BreadcrumbComponent implements OnInit {

  public breadcrumbs: IBreadcrumb[];

  /**
   * @class DetailComponent
   * @constructor
   */
  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
    this.breadcrumbs = [];
  }

  /**
   * Let's go!
   *
   * @class DetailComponent
   * @method ngOnInit
   */
  ngOnInit() {
    const ROUTE_DATA_BREADCRUMB: string = "breadcrumb";

    //subscribe to the NavigationEnd event
    this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
      //set breadcrumbs
      let root: ActivatedRoute = this.activatedRoute.root;
      this.breadcrumbs = this.getBreadcrumbs(root);
    });
  }

  /**
   * Returns array of IBreadcrumb objects that represent the breadcrumb
   *
   * @class DetailComponent
   * @method getBreadcrumbs
   * @param {ActivateRoute} route
   * @param {string} url
   * @param {IBreadcrumb[]} breadcrumbs
   */
  private getBreadcrumbs(route: ActivatedRoute, url: string="", breadcrumbs: IBreadcrumb[]=[]): IBreadcrumb[] {
    const ROUTE_DATA_BREADCRUMB: string = "breadcrumb";

    //get the child routes
    let children: ActivatedRoute[] = route.children;

    //return if there are no more children
    if (children.length === 0) {
      return breadcrumbs;
    }

    //iterate over each children
    for (let child of children) {
      //verify primary route
      if (child.outlet !== PRIMARY_OUTLET) {
        continue;
      }

      //verify the custom data property "breadcrumb" is specified on the route
      if (!child.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) {
        return this.getBreadcrumbs(child, url, breadcrumbs);
      }

      //get the route's URL segment
      let routeURL: string = child.snapshot.url.map(segment => segment.path).join("/");

      //append route URL to URL
      url += `/${routeURL}`;

      //add breadcrumb
      let breadcrumb: IBreadcrumb = {
        label: child.snapshot.data[ROUTE_DATA_BREADCRUMB],
        params: child.snapshot.params,
        url: url
      };
      breadcrumbs.push(breadcrumb);

      //recursive
      return this.getBreadcrumbs(child, url, breadcrumbs);
    }
  }

}

以上,下面我们逐行解释

Lines 1-3:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值