当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular2 (RC5) 路由与导航详解

Angular2 (RC5) 路由与导航详解

2018年05月10日  | 移动技术网IT编程  | 我要评论

守夜人5.95攻略,旺角十二金钗,小小忍者论坛

之前总结过rc4的路由配置,angular2升级rc5之后增加了ngmodule和routermodule等等很多组件,所以现在的路由配置方式也变化比较大。

1.<base href>

大多数带路由的应用都要在 的 <head>标签下顶部添加一个<base>元素。

2.配置路由器

app.routing.ts

import { routes, routermodule } from '@angular/router';
const approutes: routes = [
  {
    path: '',
    redirectto: '/dashboard',
    pathmatch: 'full'
  },
  {
    path: 'heroes',
    component: heroescomponent
  },
  {
    path: 'dashboard',
    component: dashboardcomponent
  },
  {
    path: 'detail/:id',
    component: herodetailcomponent
  }
]
export const routing = routermodule.forroot(approutes);

创建一个routes类型数组,它会把每一个url匹配到path,匹配成功则映射到该path对应的组件component上。
然后把这个路由数组approutes通过routermodule.forroot(approutes)导出。

3.引用路由

app.module.ts

import { routing } from './app.routing';

@ngmodule({
  imports: [
    browsermodule,
    routing
  ],
  declarations: [
    appcomponent
    // some component
  ],
  bootstrap: [ appcomponent ]
})
export class appmodule {}

就这样,我们在@ngmodule的imports中引用了我们配置好的路由器。

4.在模板中使用路由

完成上面的2、3步骤,我们就能在模板中使用路由了

app.component.ts

template: `
   <nav>
     <a routerlink='/dashboard' routerlinkactive='active'>dashboard</a>
     <a routerlink='/heroes' routerlinkactive='active'>heroes</a>
   </nav>
   <router-outlet></router-outlet>
`

我们在<a>标签中添加了routerlink指令,可以一次性绑定到我们路由中的path值。
如果这个url的path和routerlink匹配,就把映射到的组件在<router-outlet>中显示。

我们还可以往<a>中添加一个routerlinkactive指令,用于在相关的routerlink被激活时所在元素添加或移除css类。该指令可以直接添加到该元素上,也可以直接添加到其父元素上。

5.总结

在此,我们就完成了angular2 (rc5)的路由配置。rc5和rc4的路由配置不同之处就在于, rc5的路由不需要在设置路由模板的ts文件导入路由库

import { router_directives } from '@angular/router';

直接在ngmodule中引入配置好的路由就可以

@ngmodule({
  imports: [
    routing
  ]
})

导入的路由组件由

import { providerouter, routerconfig } from '@angular/router';

变成了

import { routes, routermodule } from '@angular/router';

路由数组的导出方式由

export const approuterproviders = [providerouter(routes)];

变成了

export const routing = routermodule.forroot(approutes);

其他部分大体上都是相同的,比如路由的数组的配置写法、routerlink指令和<router-outlet>等等。详情见我写过的rc4的路由配置方式。

以上就是对angular2 (rc5) 路由与导航的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网