1. 添加
  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. @NgModule({
  15. imports: [
  16. RouterModule.forRoot(routes)
  17. ],
  18. exports: [ RouterModule ]
  19. })
  20. export class AppRoutingModule {}

设置路由出口:

  1. <h1>{{title}}</h1>
  2. <router-outlet></router-outlet>
  • path
    • 不能以 / 开头
  • component

默认路由:

  1. { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  1. { path: 'detail/:id', component: HeroDetailComponent },

导航链接:

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

后退:

  1. this.location.back();