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
***广告***