基本路由配置
1.创建带路由的angular项目
ng new my-app
2.创建组件并配置路由
ng g component name
const routes: Routes = [
{path:'home',component:HomeComponent,},
{path:'news',component:NewsComponent},
{path:'product',component:ProductComponent},
{path:'newsContent',component:NewsContentComponent},
{path:'productContent',component:ProductContentComponent,}
];
3.页面中使用路由
<a [routerLink]="['/home']" routerLinkActive="active">首页</a>
<a [routerLink]="['/news']" routerLinkActive="active">新闻</a>
<a [routerLink]="['/productContent']" routerLinkActive="active">产品</a>
4.设置默认路由地址
const routes: Routes = [
{path:'home',component:HomeComponent, },
{path:'news',component:NewsComponent},
{path:'product',component:ProductComponent},
{path:'newsContent',component:NewsContentComponent},
{path:'productContent',component:ProductContentComponent, },
{path:'**',redirectTo:'home'}
];
路由传值
1. 静态传值
传值
<ul>
<li *ngFor="let item of list;let key = index">
<a [routerLink]="['/newsContent']" [queryParams]="{aid:key,name:'wo shi name'}">{{item}}</a>
</li>
</ul>
接收
import {ActivatedRoute} from '@angular/router'
constructor(public router:ActivatedRoute) { }
this.router.queryParams.subscribe(data=>{
console.log(data)
})
2.页面动态传值
传值
{path:'newsContent/:aid',component:NewsContentComponent},
<ul>
<li *ngFor="let item of list;let key = index">
<a [routerLink]="['/newsContent',key]">{{item}}</a>
</li>
</ul>
接收
import {ActivatedRoute} from '@angular/router'
constructor(public router:ActivatedRoute) { }
this.router.params.subscribe(data=>{
console.log(data)
})
3.js动态跳转传值
{path:'productContent/:aid',component:NewsContentComponent},
import { Router } from '@angular/router';
goProductContent(){
this.router.navigate(['/productContent/','1234'])
}
4.get传值动态跳转路由
import { Router,NavigationExtras } from '@angular/router';
getNewsContent(){
let queryParams:NavigationExtras = {
queryParams:{'aid':123}
}
this.router.navigate(['/productContent/'],queryParams)
}
父子路由
1.app-routing.moudle.ts文件中声明子路由
{
path:'home',component:HomeComponent,
children:[
{path: 'setting', component: SettingComponent},
{path: 'welcome', component: WelcomeComponent},
{path:'**',redirectTo:'welcome'}
]
},
2.父路由中嵌套子路由
<div class="product-list">
<div class="left">
<a [routerLink]="['/home/welcome']">欢迎首页</a><br><br>
<a [routerLink]="['/home/setting']">系统设置</a>
</div>
<div class="right">
<!--加载子路由界面-->
<router-outlet></router-outlet>
</div>
</div>
|