一、创建时选择router选项为yes

angular-cli中选中路由,之后app.component.html会多出

  1. <router-outlet></router-outlet>
  2. //相当于vue中
  3. <router-view></router-view>

二、一级路由

在 app-routing.module.ts 中:

  1. import { HomeComponent } from './components/home/home.component';
  2. import { AboutComponent } from './components/about/about.component';
  3. import { NewsComponent } from './components/news/news.component';
  4. import { ErrorComponent } from './components/error/error.component';//引入,需手动
  5. const routes: Routes = [
  6. {
  7. path:'home',
  8. component:HomeComponent
  9. },{
  10. path:'about',
  11. component:AboutComponent
  12. },{
  13. path:'news',
  14. component:NewsComponent
  15. },{
  16. path:'',
  17. redirectTo:"home", //路由重定向
  18. pathMatch:'full' //重定向必须写这个,类似严格模式
  19. },{
  20. path:"**", //**代表当用户输入的路由名不存在时
  21. component:ErrorComponent
  22. } //此为不匹配路由的情况发生时跳转到的路由
  23. ];
  24. //和Vue相比无太大区别,不过不用写name名

三、routerLinkActive设置routerLink默认选中的路由

  1. <ul>
  2. <li><a [routerLink]="['/home']" routerLinkActive="router-link-active">home</a></li>
  3. <li><a [routerLink]="['/news']" routerLinkActive="router-link-active">news</a></li>
  4. <li><a [routerLink]="['/about']" routerLinkActive="router-link-active">about</a></li>
  5. </ul>

四、二级路由(子路由)

  1. //app-routing.module.ts
  2. {
  3. path:'news',
  4. component:NewsComponent,
  5. children:[
  6. {
  7. path:"morning",
  8. component:MorningComponent
  9. },{
  10. path:"night",
  11. component:NightComponent
  12. },{
  13. path:"",
  14. redirectTo:"morning",
  15. pathMatch:"full"
  16. }
  17. ]
  18. }
  1. //在父路由对应的组件中的html中
  2. <router-outlet></router-outlet>