一、创建时选择router选项为yes
angular-cli中选中路由,之后app.component.html会多出
<router-outlet></router-outlet>
//相当于vue中
<router-view></router-view>
二、一级路由
在 app-routing.module.ts 中:
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { NewsComponent } from './components/news/news.component';
import { ErrorComponent } from './components/error/error.component';//引入,需手动
const routes: Routes = [
{
path:'home',
component:HomeComponent
},{
path:'about',
component:AboutComponent
},{
path:'news',
component:NewsComponent
},{
path:'',
redirectTo:"home", //路由重定向
pathMatch:'full' //重定向必须写这个,类似严格模式
},{
path:"**", //**代表当用户输入的路由名不存在时
component:ErrorComponent
} //此为不匹配路由的情况发生时跳转到的路由
];
//和Vue相比无太大区别,不过不用写name名
三、routerLinkActive设置routerLink默认选中的路由
<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>
四、二级路由(子路由)
//app-routing.module.ts
{
path:'news',
component:NewsComponent,
children:[
{
path:"morning",
component:MorningComponent
},{
path:"night",
component:NightComponent
},{
path:"",
redirectTo:"morning",
pathMatch:"full"
}
]
}
//在父路由对应的组件中的html中
<router-outlet></router-outlet>