https://angular.cn/guide/router
路由
angular-cli中选中路由,之后app.component.html会多出
<router-outlet></router-outlet>
//相当于vue中
<router-view></router-view>
一、一级路由
- 一级路由
- 路由重定向
- 不匹配路由的处理(404)
app-routing.module.ts中配置
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { NewsComponent } from './components/news/news.component';
import { AboutComponent } from './components/about/about.component';
import { ErrorComponent } from './components/error/error.component';
const routes: Routes = [
{
path:'home',
component:HomeComponent
},{
path:'news',
component:NewsComponent
},{
path:"about",
component:AboutComponent
},{
//路由重定向
path:"",
redirectTo:"home",
pathMatch:"full"
},{
// 匹配没有设置的路由
path:"**",
component:ErrorComponent
}
];
...
export class AppRoutingModule { }
二、routerLinkActive设置routerLink默认选中的路由
//app.component.html
<ul>
<li><a [routerLink]="['/home']" routerLinkActive="router-link-active">home</a></li>
<li><a [routerLink]="['/news']" routerLinkActive="router-link-active">news</a></li>
<li><a [routerLink]="['/about']" routerLinkActive="router-link-active">about</a></li>
</ul>
三、get传值
3-1 跳转
<a [routerLink]="['/detail']" [queryParams]="{id:id}">跳转detail</a>
3-2 接收 this.route.queryParams
//导入正在显示的路由
import {ActivatedRoute} from '@angular/router'
export class DetailComponent implements OnInit {
//构造函数中配置
constructor(public route:ActivatedRoute) { }
ngOnInit() {
//subscribe触发
this.route.queryParams.subscribe(res=>{
console.log(res)
})
}
}
四、动态路由
4-1 配置
//app-routing.module.ts
{
path:"detail/:id",
component:DetailComponent
}
4-2 跳转传值
//第一种跳转方式
<a [routerLink]="['/detail',id]" >跳转detail</a>
//第二种跳转方式
<a routerLink="/detail/{{id}}" >跳转detail</a>
4-3 接收 this.route.params
import {ActivatedRoute} from '@angular/router'
...
export class DetailComponent implements OnInit {
constructor(public route:ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(res=>{
console.log(res)
})
}
}
五、事件跳转
this.router.navigate
5-1 动态路由的事件跳转
<button (click)="handleClick()">跳转detail</button>
//导入路由
import {Router} from "@angular/router"
export class HomeComponent implements OnInit {
public id:string = "1213"
//配置
constructor(private router:Router) { }
handleClick(){
//跳转
this.router.navigate(['/detail',this.id])
}
}
5-2 get传值的事件跳转
//导入NavigationExtras
import {Router,NavigationExtras} from "@angular/router"
//配置 NavigationExtras的参数
export class HomeComponent implements OnInit {
public id:string = "1213"
constructor(private router:Router) { }
handleClick(){
let navigationExtras:NavigationExtras ={
queryParams:{
"id":this.id
}
}
//跳转
this.router.navigate(['/detail'],navigationExtras)
}
}
六、子路由
{
path:'news',
component:NewsComponent,
children:[
{
path:"morning",
component:MorningComponent
},{
path:"night",
component:NightComponent
},{
path:"",
redirectTo:"morning",
pathMatch:"full"
}
]
}
//在父路由对应的组件中的html中
<router-outlet></router-outlet>