Angular 2 - 導航



在 Angular 2 中,也可以執行手動導航。以下為步驟。

步驟 1 − 向 Inventory.component.ts 檔案新增以下程式碼。

import { Component } from '@angular/core'; 
import { Router }  from '@angular/router';  

@Component ({  
   selector: 'my-app',  
   template: 'Inventory 
   <a class = "button" (click) = "onBack()">Back to Products</a>' 
})  

export class AppInventory {  
   constructor(private _router: Router){} 

   onBack(): void { 
      this._router.navigate(['/Product']); 
   } 
}

需要注意以下有關上述程式的要點 −

  • 宣告一個 html 標記,其中有一個 onBack 函式標記到 click 事件。因此,當用戶單擊此標記時,他們將被導回到 Products 頁面。

  • 在 onBack 函式中,使用 router.navigate 導航到所需頁面。

步驟 2 − 現在,儲存所有程式碼並使用 npm 執行應用程式。轉到瀏覽器,你將看到以下輸出。

Application Using npm

步驟 3 − 單擊 Inventory 連結。

Inventory Link

步驟 4 − 單擊“返回產品”連結,你將獲得以下輸出,該輸出將你帶回到 Products 頁面。

Back to Products
***廣告***