<router-outlet>
的嵌套使用children
,代表子路由。<router-outlet>
,子路由的內容就會渲染在裡面。例如:
{ path: 'projects/:id', component: ProjectDetailComponent, children: [
{ path: 'info', component: ProjectInfoComponent },
{ path: 'gallery', component: ProjectGalleryComponent }
]}
loadChildren
搭配 import()
。建立兩個子元件:
ng g c components/project-info
ng g c components/project-gallery
在 app.module.ts
的 routes
調整:
const routes: Routes = [
{ path: '', component: ProjectsComponent },
{
path: 'projects/:id',
component: ProjectDetailComponent,
children: [
{ path: 'info', component: ProjectInfoComponent },
{ path: 'gallery', component: ProjectGalleryComponent },
{ path: '', redirectTo: 'info', pathMatch: 'full' } // 預設顯示 info
]
},
{ path: '**', redirectTo: '' }
];
在 project-detail.component.html
增加子導覽與嵌套的 <router-outlet>
:
<div class="container section" *ngIf="project">
<h2>{{ project.title }}</h2>
<p class="muted">{{ project.tech }}</p>
<nav class="sub-nav">
<a [routerLink]="['info']" routerLinkActive="active">資訊</a>
<a [routerLink]="['gallery']" routerLinkActive="active">圖片</a>
</nav>
<router-outlet></router-outlet>
<br />
<a routerLink="/" class="btn btn-outline">返回首頁</a>
</div>
project-info.component.html
<section>
<h3>專案介紹</h3>
<p>這裡可以放更多專案的背景描述、技術挑戰、心得。</p>
</section>
project-gallery.component.html
<section>
<h3>專案截圖</h3>
<img src="assets/demo1.png" alt="專案截圖1" width="400">
<img src="assets/demo2.png" alt="專案截圖2" width="400">
</section>
假設我們想把「Projects 區域」獨立成一個模組,只在需要時才載入。
ng g module projects --route projects --module app.module
Angular CLI 會自動產生 projects.module.ts
與路由設定。
ProjectsComponent
、ProjectDetailComponent
、ProjectInfoComponent
、ProjectGalleryComponent
移到 projects/
模組裡。projects-routing.module.ts
會包含:const routes: Routes = [
{ path: '', component: ProjectsComponent },
{ path: ':id', component: ProjectDetailComponent, children: [
{ path: 'info', component: ProjectInfoComponent },
{ path: 'gallery', component: ProjectGalleryComponent }
]}
];
在 app.module.ts
的路由:
const routes: Routes = [
{ path: '', redirectTo: 'projects', pathMatch: 'full' },
{ path: 'projects', loadChildren: () => import('./projects/projects.module').then(m => m.ProjectsModule) },
{ path: '**', redirectTo: 'projects' }
];
/projects/0/info
→ 顯示專案資訊/projects/0/gallery
→ 顯示專案圖片/projects
時才會載入,提高效能<router-outlet>
<router-outlet>
[routerLink]="'/info'"
→ 跑到根路徑[routerLink]="['info']"
→ 相對於父路由declarations
,否則會報錯Angular 階段最後一天,我們要: