Navigating Between Angular Routes

Navigating Between Angular Routes

We can use the RouterLink directive or the router.navigate or router.navigatebyUrl methods of the router service to navigate between routes in the Angular router. We'll take a closer look at these strategies in this article.

Navigating between Angular routes

In Angular, there are two ways to switch between routes.

  1. Using RouterLink Directive
  2. Via Code

RouterLink directive

In earlier courses, we looked at how to navigate using the RouterLink directive.

You can use the RouterLink directive to tie any clickable HTML element to a Route. The router will travel to the related Route when the user clicks on the HTML element.

As an example,

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

Will map to the URL "/product" and render the ProductComponent associated with it.

Navigating Using Code

You can also use the code to traverse imperatively. This is accomplished through the router service, which provides the navigate and navigatebyUrl methods for changing routes.

router.navigate

If you wish to navigate to a route using the link parameters array, use this method. The link parameters array is the first argument to the navigate method, which is similar to what we supply when defining the routerlink directive.

Unless you specify a beginning point, the Navigate Method always uses the absolute route.

navigate.navigateByUrl

If you wish to travel to a URL using the absolute path, use this approach. The first parameter is a string that contains the entire URL.

The absolute path is always used by the NavigateByUrl method.

We must inject router service into our component to leverage both of these techniques, as illustrated below.

constructor(private _router:Router){
}

After that, invoke

this._router.navigate(['product']

OR

this._router.navigateByUrl('product')

To get to the target destination.

Link Parameters array

The LINK parameters array is a collection of strings that must be sent as an argument to the routerlink directive or the navigate method in order for navigation to work.

The path of the route, as well as the route parameters that go into the route URL, must be specified.

The URL route '/product/detail/1' is resolved in the following example.

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

OR 

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

Relative and Absolute Paths in Routes

The Angular routes have a tree structure that resembles a directory.

As a result, we can utilise directory-like syntaxes in the link parameters array, such as add / (root node),./ (current node), or../ (parent node).

"/", "./", or "../" can be appended to the first segment of the link parameters array.

The path is deemed to be Absolute if the first section of the route begins with "/."

The path is considered relative if the first segment begins with "./" or if it does not begin with a slash.

The path is relative to the parent route if the first segment begins with "../". (one level higher)

router.navigate method and relative path

The absolute path is always used by the navigate method, as previously stated. We must tell the router where we are in the route tree in order for the Navigate method to work with a relative path.

As illustrated below, this is accomplished by setting the relativeTo Property to the ActivatedRoute.

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

RouterLink directive and relative path

You'd use the same link parameters array if you were using a RouterLink instead of the Router service, but you wouldn't provide the object the relativeTo attribute. In a RouterLink directive, the ActivatedRoute is implied.

Absolute Path Vs Relative Path Which one to Use?

It is suggested that you take the Relative path. If the parent URL structure changes, using an absolute path breaks our function. Even if the parent path changes, the relative path will remain unchanged.

To go to the parent route

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

To access the Sibling route

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

To take the child's path

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

NavigationExtras

Both routers can benefit from the additional settings we can supply. navigate() or router are two options. navigatebyURL() is a method that allows you to navigate by URL.

relativeTo: ActivatedRoute

Relative navigation from the current ActivatedRoute is enabled. This only applies to the router.navigate() method.

Example:

The following is a list of resources.

From the kid route, navigates to the Detail route.

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

queryParams: a set of parameters

Sets the URL's query parameters. You may learn how to pass query parameters to an Angular route in the article How to pass query parameters to an Angular route.

Example:

The URL is created as "/product?page=2" using the following code.

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

fragment: string
The hash fragment for the URL is set.

Example:

The URL is created as "/home#top" using the following code.

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

preserveQueryParams: boolean
The current route's query parameters are passed on to the next route.

Example:

If you're on the "Product?Page=2" route, clicking the link below will send the query parameters to the "view" route as "view?Page=2."

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

queryParamsHandling: QueryParamsHandling

If queryParamsHandling="merge" is set, the current route's query parameters are merged with those of the new route.

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

preserveFragment: boolean
Passes the current route's fragment to the next navigation. the same as the preserve QueryParams

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

skipLocationChange: boolean
You can alter the route without modifying the browser's URL. This takes you to a new URL without creating a new state in your browser's history.

Example:

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

replaceUrl: boolean

While traveling to the new route, the current route is deleted from the browser history. It replaces the present historical state with a new one.

Example:

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

RouterLink

Similar to the NavigationExtras directive, you can provide the RouterLink directive extra options. The settings listed below are supported.

QueryParams: Params

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

preserveQueryParams: boolean

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

queryParamsHandling : QueryParamsHandling

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

Fragment: string

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

PreserveFragment: boolean

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

SkipLocationChange: boolean

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

ReplaceUrl: boolean

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

Conclusion

We looked at different ways to traverse between Angular routes using the Angular router in this article. We'll learn how to browse using the RouterLink directive or the router service's router.navigate or router.navigatebyUrl methods. We learned how to build up path routing in both relative and absolute terms. Finally, we looked at the several alternatives that these navigation systems provide.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post