Angular Router.navigate() Method

Written by: Arvind Rai,
Last updated:
March 03, 2024
Angular Router handles the navigation from one view to another view and to manipulate URL. Find the Router methods to handle navigation.
navigateByUrl() : Navigates to a view using an absolute path.
navigate() : Navigates to a view using the given commands and a starting point.
On this page, we will learn using navigate() method in detail in our routing application.
navigate() method is used to navigate from one view to another view using specified array of commands and a starting point.
Find its method signature.
navigate(
  commands: any[],
  extras: NavigationExtras = { skipLocationChange: false }
): Promise<boolean> 

Parameters :
commands : Accepts the URL fragments using which target URL is created. Static URL can directly be specified.
extras : Optional. It determines how the URL is created. For example, use relativeTo to create relative URL. By default the value of skipLocationChange is false.

Returns :
navigate() returns a Promise of boolean. If value is true, it means navigation is successful. If value is false, it says that navigation is failed.

1. navigate() method accepts a command as an array of path segments followed by the parameters for each segments.
2. Using command we can create absolute URL as well as relative URL. If extras object contains relativeTo property, a relative URL is created.

2. NavigationExtras

Angular NavigationExtras is used to modify the router navigation strategy that contains the properties as following.
relativeTo : Specifies a root URI.
queryParams : Sets query parameters to URL.
fragment : Sets hash fragments for the URL.
queryParamsHandling : Its values are preserve and merge. When we use preserve, it preserves current parameters. When we use merge, it merges new parameters with current parameters.
preserveFragment : Accepts boolean values. When true, preserves the URL fragment for next navigation.
onSameUrlNavigation : Its values are reload and ignore. On same URL navigation, it can reload or ignore.
skipLocationChange : Accepts boolean values. When true, navigation does not push new state in the history.
replaceUrl : Accepts boolean values. When true, navigation replaces the current state in the history.
state : State defined by us that can be passed to any navigation.

3. Using navigate()

To use navigate method, inject Router using constructor in component.
1. Passing command array with one URL segment followed by path parameter.
constructor(private router: Router) {}
onButtonClick() {
	this.router.navigate(['writer', 101]);
} 
Application will navigate to below URL.
/writer/101 
2. Command with multiple segments followed by path parameters.
this.router.navigate(['writer', 101, "book", 51]); 
Created URL:
/writer/101/book/51 

4. relativeTo

Using relativeTo, we can set a root URI and then URL segments passed as command creates relative URL.
Find the code snippet to use relativeTo as extras.
constructor(private router: Router, private route: ActivatedRoute) {}
onButtonClick() {
	this.router.navigate(['state', 11, "city", 21], {relativeTo: this.route});
} 
Suppose our application is already on root URI /country and we navigate using above code, we will navigate to below URL.
/country/state/11/city/21 
Root URI /country is concatenated to relative URI.

5. queryParams

queryParams sets query parameter to URL.
this.router.navigate(['college', 10, "student", 11],
	{
		queryParams: { name: 'Mukesh', age: 15, city: 'Varanasi' },
		relativeTo: this.route
	}); 
Suppose root URI is /education , then final URL will be created as below.
/education/college/10/student/11?name=Mukesh&age=15&city=Varanasi 

6. queryParamsHandling

queryParamsHandling decides how to handle query parameters in the next navigation. It can have two values.
preserve : Preserve current parameters and discard the new parameters.
merge : Merge new parameters with current parameters.
Suppose our current URL with parameters is as below.
/company/?cid=101 
a. Using merge : New and current parameters will be merged.
this.router.navigate(['team', 15],
	{
		queryParams: { empname: 'Mukesh', age: 25 },
		relativeTo: this.route,
		queryParamsHandling: "merge"
	}); 
Created URL:
/company/team/15?cid=101&empname=Mukesh&age=25 
b. Using preserve : Current parameters will be preserved and new parameters will be discarded.
this.router.navigate(['team', 15],
	{
		queryParams: { empname: 'Mukesh', age: 25 },
		relativeTo: this.route,
		queryParamsHandling: "preserve"
	});	
Created URL:
/company/team/15?cid=101 

7. fragment

fragment sets the hash fragment for the URL.
this.router.navigate(['book', 3, 'page', 10],
	{
		fragment: 'bottom'
	}); 
Created URL :
/book/3/page/10#bottom 

8. preserveFragment

preserveFragment is a boolean property. When its value is true, URL fragment is preserved for next URL.
Suppose current URL is as below.
/worldnews#top 
Now navigate to another location using below code.
this.router.navigate(['political'],
	{
		preserveFragment: true,
		relativeTo: this.route
	}); 
Find the created URL:
/worldnews/political#top 
We can see that hash fragment is preserved.

9. skipLocationChange

skipLocationChange is a boolean property and its default value is false. When we navigate to new URL, that URL is displayed in browser. When its value is true, then navigate() method navigates to new URL silently and location change is skipped, its means browser URL will not change.
this.router.navigate(['userdetail'],
	{
		skipLocationChange: true
	}); 

10. replaceUrl

replaceUrl is boolean property. When its value is true, application navigates to the new URL by replacing the current state in the history.
this.router.navigate(['userdetail', 11],
	{
		replaceUrl: true
	}); 
Application will navigate to /userdetail/11 .

11. state

Using state, we can send data from one path to another path.
this.router.navigate(['personList'],
	{
		state: { id: 101, name: "Mohit" },
	}); 
Once we navigated on /personList, we can fetch data using Router.lastSuccessfulNavigation property.
constructor(private router: Router) { }
ngOnInit() {
	const obj = this.router.lastSuccessfulNavigation?.extras.state;
	console.log(obj);
} 
Output
{ id: 101, name: "Mohit" } 

12. References

Join the Newsletter

(Subscribe to get our latest content directly into your inbox)

WRITTEN BY
ARVIND RAI
ARVIND RAI









©2024 concretepage.com | Privacy Policy | Contact Us