
- Angular 4 教程
- Angular 4 - 首頁
- Angular 4 – 概述
- Angular 4 – 環境設定
- Angular 4 – 專案設定
- Angular 4 – 元件
- Angular 4 – 模組
- Angular 4 – 資料繫結
- Angular 4 – 事件繫結
- Angular 4 – 模板
- Angular 4 – 指令
- Angular 4 – 管道
- Angular 4 - 路由
- Angular 4 – 服務
- Angular 4 – Http 服務
- Angular 4 – 表單
- Angular 4 – 動畫
- Angular 4 – 材料
- Angular 4 – CLI
- Angular 4 – 示例
- Angular 4 有用資源
- Angular 4 - 快速指南
- Angular 4 - 有用資源
- Angular 4 - 討論
Angular 4 - 路由
路由基本上意味著在頁面之間導航。您已經看到許多帶有連結的網站,這些連結會將您引導到新頁面。這可以透過路由來實現。這裡我們提到的頁面將以元件的形式存在。我們已經瞭解瞭如何建立元件。現在讓我們建立一個元件,並瞭解如何使用路由。
在主父元件app.module.ts中,我們現在必須包含路由器模組,如下所示:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule} from '@angular/router'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
import { RouterModule} from '@angular/router'
在這裡,RouterModule 從 angular/router 匯入。該模組包含在匯入中,如下所示:
RouterModule.forRoot([ { path: 'new-cmp', component: NewCmpComponent } ])
RouterModule 指的是forRoot,它接收一個數組作為輸入,該陣列又包含路徑和元件的物件。路徑是路由器的名稱,元件是類的名稱,即建立的元件。
現在讓我們看看建立的元件檔案:
New-cmp.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created"; constructor() {} ngOnInit() { } }
突出顯示的類在主模組的匯入中提到。
New-cmp.component.html
<p> {{newcomponent}} </p> <p> new-cmp works! </p>
現在,我們需要在需要時或從主模組單擊時顯示 html 檔案中的上述內容。為此,我們需要在app.component.html中新增路由器詳細資訊。
<h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b><br/> <b>Square root of 729 is: {{729 | sqrt}}</b> <br /> <br /> <br /> <a routerLink = "new-cmp">New component</a> <br /> <br/> <router-outlet></router-outlet>
在上面的程式碼中,我們建立了錨鏈接標籤,並將 routerLink 設定為“new-cmp”。這在app.module.ts中作為路徑引用。
當用戶點選新元件時,頁面應該顯示內容。為此,我們需要以下標籤 - <router-outlet> </router-outlet>。
上述標籤確保當用戶點選新元件時,new-cmp.component.html中的內容將顯示在頁面上。
現在讓我們看看輸出如何在瀏覽器中顯示。

當用戶點選新元件時,您將在瀏覽器中看到以下內容。

url 包含https://:4200/new-cmp。在這裡,new-cmp 附加到原始 url,這是app.module.ts中給出的路徑和app.component.html中的 router-link。
當用戶點選新元件時,頁面不會重新整理,內容會在沒有任何重新載入的情況下顯示給使用者。只有點選時才會重新載入網站程式碼的特定部分。當頁面上有大量內容並且需要根據使用者互動載入時,此功能很有幫助。此功能還提供了良好的使用者體驗,因為頁面沒有重新載入。