建立路由範例


步驟程式碼範例:

1.新建附有路由模組app-routing.module.ts檔案的專案

ng new testRouter1 --routing
npm install

2.src/app內可看到app-routing.module.ts檔案,裡面程式如下:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    children: []
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

3.在app.module.ts檔案可看到下面程式碼,代表appModule有載入路由模組

import { AppRoutingModule } from './app-routing.module';
@NgModule({
  imports: [
    AppRoutingModule
  ],
})

4.在app.component.html檔案可看到下面程式碼,裡面的<router-outlet></router-outlet>是路由插座,在app-routing.module.ts設定的路由頁面會顯示在此區塊

<h1>
  {{title}}
</h1>
<router-outlet></router-outlet>

5.建立兩個component作為兩個獨立頁面

ng g c page-a
ng g c page-b

6.在app-routing.module.ts設定page-a與page-b的路由

const routes: Routes = [
  {
    path: 'pageA',
    component: PageAComponent
  },
  {
    path: 'pageB',
    component: PageBComponent
  }
];

7.啟動server

npm start

8.在瀏覽器網址列輸入localhost:4200/ 進行預覽

9.在瀏覽器網址列輸入localhost:4200/pageA 進行預覽

10.在瀏覽器網址列輸入localhost:4200/pageB 進行預覽

11.在app.component.html設定page-a與page-b的超連結

<h1>
  {{title}}
</h1>
<ul>
  <li><a [routerLink]="['/pageA']">來去page-a</a></li>
  <li><a [routerLink]="['/pageB']">來去page-b</a></li>
</ul>
<router-outlet></router-outlet>

12.測試上面設定的page-a與page-b超連結

results matching ""

    No results matching ""