基本用法

  1. 添加 AppRoutingModule
  1. ng generate module app-routing --flat --module=app

app-routing.module.ts

  1. import { NgModule } from '@angular/core';
  2. import { RouterModule, Routes } from '@angular/router';
  3. import { FooComponent } from './foo/foo.component'
  4. import { BarComponent } from './bar/bar.component'
  5. const routes: Routes = [
  6. {
  7. path: 'foo',
  8. component: FooComponent
  9. },
  10. {
  11. path: 'bar',
  12. component: BarComponent
  13. }
  14. ]
  15. @NgModule({
  16. imports: [
  17. RouterModule.forRoot(routes)
  18. ],
  19. exports: [ RouterModule ]
  20. })
  21. export class AppRoutingModule {}

设置路由出口:

  1. <h1>{{title}}</h1>
  2. <router-outlet></router-outlet>

设置导航链接:

  1. <ul>
  2. <li>
  3. <a routerLink="/foo">Go Foo</a>
  4. </li>
  5. <li>
  6. <a routerLink="/bar">Go Foo</a>
  7. </li>
  8. </ul>

路由对象

  • path
    • 不能以 / 开头
  • component

默认路由:

  1. { path: '', redirectTo: '/dashboard', pathMatch: 'full' },

动态路由匹配

动态路径配置:

  1. { path: 'detail/:id', component: HeroDetailComponent },

导航链接:

  1. <a *ngFor="let hero of heroes" class="col-1-4"
  2. routerLink="/detail/{{hero.id}}">

在组件中解析获取动态路径参数:

  1. import { Component, OnInit } from '@angular/core';
  2. import { ActivatedRoute } from '@angular/router';
  3. import { Location } from '@angular/common';
  4. @Component({
  5. selector: 'app-user',
  6. templateUrl: './user.component.html',
  7. styleUrls: ['./user.component.css']
  8. })
  9. export class UserComponent implements OnInit {
  10. constructor(
  11. private route: ActivatedRoute,
  12. private location: Location
  13. ) { }
  14. ngOnInit() {
  15. const id = this.route.snapshot.paramMap.get('id')
  16. console.log(id)
  17. }
  18. }

路由导航

后退:

  1. this.location.back();