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 函数。 因此,当用户单击此按钮时,他们将被引导回"产品"页面。

  • 在onBack函数中,使用router.navigate导航到所需页面。

步骤 2 − 现在,保存所有代码并使用 npm 运行应用程序。 转到浏览器,您将看到以下输出。

使用 npm 的应用程序

步骤 3 − 单击库存链接。

库存链接

步骤 4 − 单击"返回产品"链接,您将获得以下输出,返回"产品"页面。

返回产品