本篇介紹使用routeLink在兩個Component template間切換。
Angular專案建好後把app.component.html的預設內容刪除,
只留下<router-outlet></router-outlet>。
app.component.html
<router-outlet></router-outlet>
接著用Angular CLI建立兩個Component,第一個是FirstComponent,第二個是SecondComponent。
然後開啟app-routing.module.ts,
在變數routes: Routes中新增路由到FirstComponent及SecondComponent的path,分別為:
- 導向FirstComponent:
{path:'first', component:FirstComponent} - 導向SecondComponent:
{path:'second', component:SecondComponent}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FirstComponent } from './first/first.component'; // <-- import
import { SecondComponent } from './second/second.component'; // <-- import
const routes: Routes = [
{path:'first', component:FirstComponent}, // to FirstComponent
{path:'second', component:SecondComponent} // to SecondComponent
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
完成Routes設定後,當URL輸入對應路徑(path)時,Angular Router會根據路徑顯示對應的Component template。
在瀏覽器輸入http://localhost:4200/first會導向FirstComponent的template;
在瀏覽器輸入http://localhost:4200/second會導向SecondComponent的template。
接著在first.component.html及second.component.html利用<a>搭配routeLink路由至另一個Component。
修改first.component.html如下。
first.component.html
<p>
first works!
</p>
<p>Route link <a routerLink="/second">to SecondComponent</a></p>
修改second.component.html如下。
second.component.html
<p>
second works!
</p>
<p>Route link <a routerLink="/first">to FirstComponent</a></p>
完成後在瀏覽器輸入http://localhost:4200/first導向FirstComponent的template頁面。
點選first.component.html中的to SecondComponent連結可切換至second.component.html。
點選second.component.html中的to FirstComponent連結又會切換回first.component.html。
你可能會注意到如果<a>使用href屬性也是可以導向另一個頁面,例如下面把原來的routerLink改成href指向另個頁面的連結。
first.component.html
<p>
first works!
</p>
<p>Route link <a href="/second">to SecondComponent</a></p>
second.component.html
<p>
second works!
</p>
<p>Route link <a href="/first">to FirstComponent</a></p>
不過開啟瀏覽器的開發模式的[Network]比較一下就可以發現routerLink與href的差別。routerLink是Angular的內部路由並不會重新載入整個頁面,這也是Angular作為單頁應用程式(SPA)框架的重要特色;而href是HTML元素屬性,每次點選時都會重新載入連結頁面的資源,整個頁面會被重新刷新,而非載入部分內容。
參考:
沒有留言:
張貼留言