Angular - 導航



在 Angular 中,也可以進行手動導航。以下是步驟。

步驟 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 函式。因此,當用戶點選此標籤時,他們將被引導回 Products 頁面。

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

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

Application Using npm

步驟 3 - 點選 Inventory 連結。

Inventory Link

步驟 4 - 點選“返回產品”連結,您將獲得以下輸出,這將帶您返回 Products 頁面。

Back to Products
廣告