目标
实现这样一个页面,通过路由跳转不同界面
// 创建项目
ng new demo --routing
// 创建component
ng g component components/index
ng g component components/container
ng g component components/shop
ng g component components/shopList
ng g component components/shopManager
路由配置 使用RouterLink跳转
在app-routing-module.ts中:
const routes: Routes = [
{
path:"index",
component:IndexComponent,
children: // 父子路由
[
{
path:"**", // 默认页面
component:ContainerComponent
}
]
},
{
path:"shop",
component:ShopComponent,
children:
[
{
path:"shopList",
component:ShopListComponent
},
{
path:"shopManager",
component:ShopManagerComponent
}
]
},
{
path:"**",
redirectTo:"/index" // 重定向
}
];
在app.component.html中:
<h1>
<a routerLink="/index" routerLinkActive="active">首页</a>
<a routerLink="/shop" routerLinkActive="active">商品</a>
</h1>
<router-outlet></router-outlet>
注意使用<router-outlet></router-outlet>
来表明在什么地方界面路由页面
在shop.component.html中:
<div class="left">
<ul>
<li>
<a routerLink="/shop/shopList" routerLinkActive="active">商品列表</a>
</li>
<li>
<a routerLink="/shop/shopManager" routerLinkActive="active">商品管理</a>
</li>
</ul>
</div>
<div class="right">
<router-outlet></router-outlet>
</div>
动态路由中传值
先创建一个商品详情组件:
ng g component components/shopInfo
配置路由:
{
path:"shopInfo/:id", // 动态传值
component:ShopInfoComponent
}
// html文件中:
<ul>
<li *ngFor="let item of list;let i = index">
<a routerLink="/shopInfo/{{item.id}}">{{item.name}}</a>
</li>
</ul>
获取传值
首先在要获取值的页面引入ActivatedRoute:
import { ActivatedRoute} from "@angular/router";
constructor(private route:ActivatedRoute)
{
}
ngOnInit()
{
//console.log(this.route.params);
// 获取的是个Observable对象
this.route.params.subscribe(function(data)
{
console.log(data);
});
}
js跳转
需要跳转的页面引入Router依赖
import { Router} from "@angular/router";
constructor(private router:Router) { }
// html 文件中:
<button (click)="onClick()">js跳转</button>
// ts文件中:
onClick()
{
this.router.navigate(["/hot"]);
}
js跳转传值
import { Router,NavigationExtras} from "@angular/router";
constructor(private router:Router) { }
// html 文件中:
<button (click)="onClick(123456)">js跳转</button>
// ts文件中:
onClick(id)
{
let navigationExtras:NavigationExtras={
queryParams:{"id":id}
};
this.router.navigate(["/hot"],navigationExtras);
}
接收js跳转传值
import { ActivatedRoute} from "@angular/router";
constructor(private routed:ActivatedRoute) { }
ngOnInit()
{
this.routed.queryParams.subscribe(function(data)
{
console.log(data);
});
}