一,概述
路由就是根据不同的url地址,动态的让根组件挂载其他组件来实现一个单页面应用
二,使用
1,创建项目时注意选择创建路由--yes
2,在app-routing.module.ts中引入需要配置路由的组件,然后声明访问路径
import { HomeComponent } from './components/home/home.component';
import { HeaderComponent } from './components/header/header.component';
import { NewsComponent } from './components/news/news.component';
import { NewDetailComponent } from './components/new-detail/new-detail.component';
import { HeaderDetailComponent } from './components/header-detail/header-detail.component';
const routes: Routes = [
{
path:'home',component:HomeComponent
},{
path:'header',component:HeaderComponent
},{
path:'news',component:NewsComponent
},{
path:'',component:HomeComponent
},{
path:'newsDetail/:id',component:NewDetailComponent
},{
path:'headerDetail/:id',component:HeaderDetailComponent
}
];
另外可以设置匹配不到路由的跳转页面
//匹配不到路由的时候加载的组件或者跳转的路由
{path:'**',redirectTo:'home'}
3,找到app.component.html根组件模板,配置router-outlet显示动态加载的路由
<h1>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
</h1>
<router-outlet></router-outlet>
4,设置选中高亮(或者其他)样式
<h1> <a routerLink="/home" routerLinkActive="active">首页</a> <a routerLink="/news" routerLinkActive="active">新闻</a> </h1> <router-outlet></router-outlet>
设置样式
.active{
color: red;
}
三,父子路由
{path:'',component:ProductComponent,
children:[
{path:'cart', component: CartComponent},
{path: "pcontent",component: PcontentComponent}
]
}