Router.navigate vs Router.navigateByUrl




Asked on March 05, 2024

What is difference between Router.navigate() and Router.navigateByUrl() functions? When should I use Router.navigate() and when should I use Router.navigateByUrl() ?




Replied on March 05, 2024

1. navigate() accepts an array of URL segments followed by path parameter whereas navigateByUrl() accepts an absolute URL to navigate.


2. Using navigate() :


Suppose I need to navigate to a state detail with id 5 of a country with id 11. Then create URL as following.


constructor(private router: Router) { }

onButtonClick() {

   this.router.navigate(['country’, 11, ‘state’, 5]);

}


We will be navigated to /country/11/state/5


3. As navigateByUrl() needs an absolute path, so pass it as following.


onButtonClick() {

this.router.navigateByUrl('/country/11/state/5');

}


4.  The second optional parameter of navigate() is NavigationExtras that inherits UrlCreationOptions and NavigationBehaviorOptions whereas the second optional parameter of navigateByUrl() is only NavigationBehaviorOptions.


5. The properties of UrlCreationOptions are relativeTo, queryParams, fragment, queryParamsHandling, and preserveFragment.


6. The properties of NavigationBehaviorOptions are onSameUrlNavigation, skipLocationChange, replaceUrl, state and info.


7. Code snippet for navigate() with NavigationExtras.


this.router.navigate(['college’, 11],

 {

   queryParams: { principal: 'Mukesh', noOfStd: 150},

   relativeTo: this.route,

   skipLocationChange: true,

   replaceUrl: true

 });



8. Code snippet for navigateByUrl() with NavigationBehaviorOptions.


this.router.navigateByUrl('/college/11',

  {

     skipLocationChange: true,

     replaceUrl: true

   });



Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us