這篇來看看如何使用Roting來切換頁面
透過Routing可以決定所要顯示的Page,Angular裡我們會在app-routing.module.ts設定相關Routing,
下圖是沒設定出現找不到符合Route錯誤訊息

現在我需要幫Home和About設定相關routing
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'about',
    component: AboutComponent
  }
];
@NgModule({
  imports: [RouterModule.forRoot(
    routes ,
    { enableTracing: true } // <-- debugging purposes only
  )],
  exports: [RouterModule]
})
修改app.component.html
<ul>
  <li>
    <a [routerLink]="['']">Home</a>
  </li>
  <li>
      <a [routerLink]="['about']">About</a>
  </li>
</ul>
<router-outlet></router-outlet>
這樣我們就完成Home和About頁面的routing
使用參數
如果我需要瀏覽About並帶Name參數是否可行呢?一樣透過Routing取得即可,同時我也需要返回Home的操作
{
    path: 'about/:name',
    component: AboutComponent
  }
<li>
      <a [routerLink]="['about/rico']">About</a>
  </li>
About.component.ts修改如下
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
export class AboutComponent implements OnInit {
  Name = '';
  constructor(private route: ActivatedRoute, private router: Router) {
    this.route.params.subscribe(res => {
      this.Name = res.name;
      console.log(res.name);
    });
  }
  ngOnInit() {
  }
  backToHome() {
    this.router.navigate(['']);
  }
}
About.component.html修改如下
<p>
  I am <strong style="color: green">{{Name}}</strong> , about works!<br/>
  <a href="" (click)="backToHome()"><strong>Back To Home</strong></a>
</p>
結果

參考