• Skip to content
  • Skip to primary sidebar
  • Home
  • Angular
  • ASP.NET Core
  • Entity Framework
    • Entity Framework 6
    • Entity Framework Core
  • Crystal Reports
  • C#
  • ASP.NET
  • About Us
    • Privacy Policy
    • Contact Us

TekTutorialsHub

Free Online Tutorials

Navigating between Angular routes

May 21, 2017 by TekTutorialsHub Leave a Comment

Passing Optional Parameters
Angular Route Guards
 

The Angular router allows us to navigate between the routes using either RouterLink directive or imperatively using router.navigate or router.navigatebyUrl method of the router service.

In this tutorial, we look at these methods more closely.

In this article

  • Navigating between Angular routes
    • RouterLink directive
    • Navigating Using Code
      • router.navigate
    • Link Parameters array
  • Relative and Absolute Paths in Routes
    • router.navigate method and relative path
    • RouterLink directive and relative path
    • Absolute Path Vs Relative Path Which one to Use?
  • NavigationExtras
  • RouterLink
    • Conclusion

Navigating between Angular routes

You can navigate between routes in Angular 2 in two ways

  1. Using RouterLink Directive
  2. Via Code

RouterLink directive

We looked at how to navigate using the RouterLink directive in the previous tutorials.

The RouterLink is a directive, which you can use to bind any clickable HTML element to a Route. When the user clicks on the HTML element the router will navigate to the associated Route.

For Example

1
2
3
 
<li><a [routerLink]="['product']">Product</a></li>
 

Will map to URL “/product” and renders the associated ProductComponent

Navigating Using Code

You can also navigate imperatively by using the code. This is done using the router service, which provides navigate and navigatebyUrl methods via which you can perform route changes.

router.navigate

Use this method, if you want to Navigate to a route using the link parameters array. The first argument to the navigate method is link parameters array, which is similar to what we provide while defining the routerlink directive

Navigate Method always uses the absolute path unless you provide a starting point.

navigate.navigateByUrl

Use this method if you want to navigate to a URL by using the absolute path. The first argument is a string containing the complete URL.

NavigateByUrl Method always uses the absolute path

To use both these methods, we need to inject router service into our component as shown below

1
2
3
4
 
constructor(private _router:Router){
}
 

And then invoke

1
2
3
 
this._router.navigate(['product']
 

Or

1
2
3
 
this._router.navigateByUrl('product')
 

To navigate to the desired route.

Link Parameters array

LINK Parameters array is an array of strings, which you must specify as argument to either to routerlink directive or navigate method for navigation to work

We need to specify the path of the route and route parameters that go into the route URL.

The following example resolves to the URL path ‘/product/detail/1’

1
2
3
 
<li><a [routerLink]="['product/detail/1']">Product 1 Overview</a></li>
 

or

1
2
3
 
this._router.navigate(['product/detail/1'])
 

Relative and Absolute Paths in Routes

The Angular routes resemble directory-like tree structure.

Hence, We can use directory like syntaxes like add / (root node) , ./ (current node) or ../ (Parent node) in the link parameters array

The First segment of the link parameters array can be prepended with “/“, “./“, or “../”

If the First segment of the route starts with “/“, then the path is considered to be Absolute path

If the First segment begins with “./” or it does not begin with a slash, then the path is considered to be the relative path.

And if the First segment begins with “. ./“, then the path is relative to the parent route. (one level up)

router.navigate method and relative path

As mentioned earlier navigate method always uses the absolute path. To make Navigate method work with a relative path, we must let know the router where are we in the route tree.

This done by setting the relativeTo Property to the ActivatedRoute as shown below

1
2
3
 
this._router.navigate(['detail'], { queryParams: { pageNum: this.pageNum + 1 }, relativeTo: this._Activatedroute } );
 

RouterLink directive and relative path

If you were using a RouterLink to navigate instead of the Router service, you’d use the same link parameters array, but you wouldn’t provide the object with the relativeTo property. The ActivatedRoute is implicit in a RouterLink directive.

Absolute Path Vs Relative Path Which one to Use?

It is recommended to use the Relative path. Using absolute path breaks our code if the parent URL structure changes. The relative path will not change even if the parent path changes

To go to the parent route

1
2
3
 
<li><a [routerLink]="['../']">Back</a></li>
 

To go to the Sibling route

1
2
3
 
<li><a [routerLink]="['../<sibling>']">Goto sibling</a></li>
 

To go to the child route

1
2
3
 
<li><a [routerLink]="['<Child>']">Goto Child</a></li>
 

NavigationExtras

We can provide the extra options to both router.navigate() or router.navigatebyURL() method.

relativeTo: ActivatedRoute

Enables relative navigation from the current ActivatedRoute. This is applicable only to router.navigate() method.

Example:

The following Navigates to the Detail route from child route

1
2
3
 
this.router.navigate(['../Detail'], { relativeTo: this.activatedRoute });
 

queryParams: Params

Sets query parameters to the URL. You can refer to the tutorial How to pass query parameters to Angular route

Example:

The following code constructs the URL as “/product?page=2”.

1
2
3
 
this.router.navigate(['/products'], { queryParams: { page: 1 } });
 

fragment: string
Sets the hash fragment for the URL.

Example:

The following code constructs the URL as “/home#top”

1
2
3
 
this.router.navigate(['/home'], { fragment: 'top' });
 

preserveQueryParams: boolean
Passes the query parameters of the current route to the next route

Example:

If you are on the route “Product?Page=2”, then the clicking on the following will pass the query parameters to the “view” route as “view?Page=2”

1
2
3
 
this.router.navigate(['/view'], { preserveQueryParams: true });
 

queryParamsHandling: QueryParamsHandling

The query parameters of the current route are merged with that of the new route if you set queryParamsHandling=”merge”.

1
2
3
 
this.router.navigate(['/view'], { queryParams: { page: 2 },preserveQueryParams: true, queryParamsHandling: "merge" });
 

preserveFragment: boolean
Passes the fragment of the current route to the next navigation. Similar to the preserveQueryParams

1
2
3
 
this.router.navigate(['/view'], { preserveFragment: true });
 

skipLocationChange: boolean
You can change the route, without changing the URL in the browser.  This Navigates to a new URL without pushing a new state into history.

Example:

1
2
3
 
this.router.navigate(['/view'], { skipLocationChange: true });
 

replaceUrl: boolean
The current route is removed from the browser history while navigating to the new route. It replaces the current state in history with the new state.

Example:

1
2
3
 
this.router.navigate(['/view'], { replaceUrl: true });
 

RouterLink

You can provide the extra options to the RouterLink directive, similar to the NavigationExtras. The following options are supported

QueryParams: Params

1
2
3
 
<a [routerLink]="['product']" [queryParams]="{ page:2}" }>Page 2</a>
 

preserveQueryParams:boolean

1
2
3
 
<a [routerLink]="['product']" { preserveQueryParams: "true" }">Page 2</a>
 

queryParamsHandling : QueryParamsHandling

1
2
3
 
<a [routerLink]="['product']" { queryParams: { page: 2 }, queryParamsHandling: "merge" }">Page 2</a>
 

Fragment: string

1
2
3
 
<a [routerLink]="['product']" { fragment: 'top' }">Page 2</a>
 

PreserveFragment: boolean

1
2
3
 
<a [routerLink]="['product']" { preserveFragment: true }">Page 2</a>
 

SkipLocationChange: boolean

1
2
3
 
<a [routerLink]="['product']" { skipLocationChange: true">Page 2</a>
 

ReplaceUrl: boolean

1
2
3
 
<a [routerLink]="['product']" { replaceUrl: true">Page 2</a>
 

Conclusion

In this tutorial, we looked at various ways you can navigate between Angular routes, using the Angular router.  We learn how to navigate using either RouterLink directive or using router.navigate or router.navigatebyUrl method provided by the router service. We learned how to set up relative and absolute path routing. Finally, we looked at the various options that are provided by these navigation methods.

Passing Optional Parameters
Angular Route Guards
 

Filed Under: Angular Tagged With: Router

Leave a Reply

wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.
wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of

Primary Sidebar

Copyright ©2008-2018

About us Contact Privacy Policy

Feb,22,2019 11:32:04 AM

Copyright © 2019 · Magazine Pro on Genesis Framework · WordPress · Log in

wpDiscuz
Our web site uses cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.OkRead more