本篇文章主要介绍了详解angular2实现ng2-router 路由和嵌套路由,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
实现ng2-router路由,嵌套路由
首先配置angular2的时候router模块已经下载,只需要引入即可
import {RouterModule, Routes} from "@angular/router";
我们要创建一个嵌套路由,所以需要创建以下文件
- index.html
- app.module.ts
- app.component.ts
- home.component.ts
- list.component.ts
- list-one.component.ts
- list-two.component.ts
实现效果:
- 路由,单机“首页”加载home.component.ts
- 单机"列表“加载list.component.ts
- 列表中包含嵌套路由,tab页
- 单机"标签一"加载list-one.component.ts
- 单机"标签二"加载list-one.component.ts
开始配置
index.html界面配置两点
引入路由代码显示标签 引入主组件标签
就这么简单, index.html界面配置完毕
app.module.ts界面配置路由
import {BrowserModule} from "@angular/platform-browser"; import {NgModule} from "@angular/core"; import {RouterModule, Routes} from "@angular/router"; // 表单 双向数据绑定 import {FormsModule} from "@angular/forms"; import {AppComponent} from "./app.component"; // List中包含两个tab子组件 import {ListComponent} from "./list.component"; import {ListOneComponent} from "./list-one.component"; import {ListTwoComponent} from "./list-two.component"; import {HomeComponent} from "./home.component"; // 定义路由, bootstrap默认加载组件就是AppComponent,所以他就是主页导航页,然后添加的路由都在他的模板中。 // 可以所有代码写在NgModule中, 也可以这样自定义常量,然后使用。 // 定义常量 嵌套自路由 const appChildRoutes: Routes = [ {path: "one", component: ListOneComponent}, {path: "two", component: ListTwoComponent}, // 如果地址栏中输入没有定义的路由就跳转到one路由界面 { path: '**', redirectTo: "one" } ]; // 定义常量 路由 const appRoutes:Routes = [ {path: '', component: HomeComponent}, { path: 'list', component: ListComponent, children: appChildRoutes ]; // 引用定义的路由 @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot(appRoutes) ], declarations: [ AppComponent, ListComponent, HomeComponent, ListOneComponent, ListTwoComponent ], bootstrap: [AppComponent] }) export class AppModule { }
这样就完成了嵌套路由的配置
显示路由内容
app.component.ts
import {Component} from "@angular/core"; @Component({ selector: "my-app", // templateUrl: "../views/one.html" template: `` }) export class AppComponent { }
list.component.ts
import {Component} from "@angular/core"; @Component({ selector: "my-list", // templateUrl: "../views/list.html" template: ` ` }) export class ListComponent { name = "list"; }
list-one.component.ts
import {Component} from "@angular/core" @Component({ selector: "my-list-one", template:` {{name}} ` }) export class ListOneComponent { name = "list-one"; }
list-two.component.ts同理
获取路由参数id (about:id) 添加模块 ActivatedRoute
import {ActivatedRoute} from "@angular/router"; export class AboutList { id: Object; constructor(public route:ActivatedRoute) { this.id = {}; } ngOnInit() { this.route.params.subscribe(params => { this.id = params // {id: "xxx"} }); } }
直接获取id值
this.route.snapshot.params["id"] 补助: 路由中的界面跳转 import {Router} from "@angular/router"; constructor(public router: Router) { // 相当于window.location.href,界面跳转 router.navigateByUrl('home'); }
以上就是详解angular2实现ng2-router 路由和嵌套路由的详细内容,更多请关注易知道|edz.cc其它相关文章!