English 中文(简体)
Angular 2 - Navigation
  • 时间:2024-09-17

Angular 2 - Navigation


Previous Page Next Page  

In Angular 2, it is also possible to carry out manual navigation. Following are the steps.

Step 1 − Add the following code to the Inventory.component.ts file.

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

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

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

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

The following points need to be noted about the above program −

    Declare an html tag which has an onBack function tagged to the cpck event. Thus, when a user cpcks this, they will be directed back to the Products page.

    In the onBack function, use the router.navigate to navigate to the required page.

Step 2 − Now, save all the code and run the apppcation using npm. Go to the browser, you will see the following output.

Apppcation Using npm

Step 3 − Cpck the Inventory pnk.

Inventory Link

Step 4 − Cpck the ‘Back to products’ pnk, you will get the following output which takes you back to the Products page.

Back to Products Advertisements