详解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中,也可以这样自定义常量,然后使用。 //定义常量嵌套自路由 constappChildRoutes:Routes=[ {path:"one",component:ListOneComponent}, {path:"two",component:ListTwoComponent}, //如果地址栏中输入没有定义的路由就跳转到one路由界面 { path:'**',redirectTo:"one" } ]; //定义常量路由 constappRoutes: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] }) exportclassAppModule{ }
这样就完成了嵌套路由的配置
显示路由内容
app.component.ts
import{Component}from"@angular/core"; @Component({ selector:"my-app", //templateUrl:"../views/one.html" template:`` }) exportclassAppComponent{ }首页 联系我们 产品
list.component.ts
import{Component}from"@angular/core"; @Component({ selector:"my-list", //templateUrl:"../views/list.html" template:`` }) exportclassListComponent{ name="list"; }one two
list-one.component.ts
import{Component}from"@angular/core" @Component({ selector:"my-list-one", template:` {{name}} ` }) exportclassListOneComponent{ name="list-one"; }
list-two.component.ts同理
获取路由参数id(about:id)添加模块ActivatedRoute
import{ActivatedRoute}from"@angular/router"; exportclassAboutList{ id:Object; constructor(publicroute: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(publicrouter:Router){ //相当于window.location.href,界面跳转 router.navigateByUrl('home'); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。