子路由


說明

1. 可在某個路由下設定次要路由

程式語法:

const routes: Routes = [
  {
    path: '父路由',
    children: [
      {
        path: '子路由1',
        component: 某個元件
      },
      {
        path: '子路由2',
        component: 某個元件
      },

    ]
  }
];

程式碼範例:

1.建立c1與c2兩個元件

ng g c c1
ng g c c2

2.將app-routing.module.ts內的路由設定變更為如下:

const routes: Routes = [
  {
    path: '',
    redirectTo: "/pageA",
    pathMatch: "full"
  },
  {
    path: 'pageA',
    component: PageAComponent
  },
  {
    path: 'pageB',
    component: PageBComponent
  },
  {
    path: 'pageC',
    children: [
      {
        path:'',
        redirectTo: 'c1',
        pathMatch: 'full'
      },
      {
        path:'c1',
        component: C1Component
      },
      {
        path:'c2',
        component: C2Component
      }
    ]
  },
  {
    path: 'error',
    component: ErrorComponent
  },
  errorRoute
];

2.在瀏覽器網址列輸入localhost:4200/pageC/c1localhost:4200/pageC/c2測試

3.在app.component.html第11行的<a>標籤中,變更為以下html碼

<a [routerLink]="['/pageC']" [routerLinkActiveOptions]="{exact: true}" class="ripple">

4.在app.component.html第12、13行的<ul>標籤中,放入以下html碼

<li><a [routerLink]="['/pageC', 'c1']" routerLinkActive="activeStyle" [routerLinkActiveOptions]="{exact: true}">來去page-c1</a></li>
<li><a routerLink="/pageC/c2" routerLinkActive="activeStyle" [routerLinkActiveOptions]="{exact: true}">來去page-c2</a></li>

5.測試子路由來去page-c1來去page-c2三個超連結

results matching ""

    No results matching ""