How to use router.navigateByUrl and router.navigate in Angular

AngularRoutesRouterlink

Angular Problem Overview


https://angular.io/api/router/RouterLink gives a good overview of how to create links that will take the user to a different route in Angular4, however I can't find how to do the same thing programmatically rather needing the user to click a link

Angular Solutions


Solution 1 - Angular

routerLink directive as used like this:

<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>

is just a wrapper around imperative navigation using router and its navigateByUrl method:

router.navigateByUrl('/inbox/33/messages/44')

as can be seen from the sources:

export class RouterLink {
  ...

  @HostListener('click')
  onClick(): boolean {
    ...
    this.router.navigateByUrl(this.urlTree, extras);
    return true;
  }

So wherever you need to navigate a user to another route, just inject the router and use navigateByUrl method:

class MyComponent {
   constructor(router: Router) {
      this.router.navigateByUrl(...);
   }
}

There's another method on the router that you can use - navigate:

router.navigate(['/inbox/33/messages/44'])

###difference between the two

> Using router.navigateByUrl is similar to changing the location bar > directly–we are providing the “whole” new URL. Whereas > router.navigate creates a new URL by applying an array of passed-in > commands, a patch, to the current URL. > > To see the difference clearly, imagine that the current URL is > '/inbox/11/messages/22(popup:compose)'.

> With this URL, calling > router.navigateByUrl('/inbox/33/messages/44') will result in > '/inbox/33/messages/44'. But calling it with > router.navigate(['/inbox/33/messages/44']) will result in > '/inbox/33/messages/44(popup:compose)'.

Read more in the official docs.

Solution 2 - Angular

router.navigate vs router.navigateByUrl

router.navigate is just a convenience method that wraps router.navigateByUrl, it boils down to:

navigate(commands: any[], extras) {
    return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}

As mentioned in other answers router.navigateByUrl will only accept absolute URLs:

// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})

All the relative calculations are done by router.createUrlTree and router.navigate. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".." - go up, "path" - go down, {expand: true} - add query param, etc.. You can use it like this:

// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});

That {relativeTo: route} parameter is important as that's what router will use as the root for relative operations.

Get it through your component's constructor:

  // In my-awesome.component.ts:

  constructor(private route: ActivatedRoute, private router: Router) {}
  
  // Example call
  onNavigateClick() {
    // Navigates to a parent component
    this.router.navigate([..], { relativeTo: this.route })
  }

Nicest thing about this directive is that it will retrieve the ActivatedRoute for you. Under the hood it's using already familiar:

router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });

Following variants will produce identical result:

[routerLink]="['../..']"

// if the string parameter is passed it will be wrapped into an array
routerLink="../.."

Solution 3 - Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

/**
 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 *
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 *
 * ### Usage
 *
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 *
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 *
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.
 */

The Router Guide has more details on programmatic navigation.

Solution 4 - Angular

From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .


router.navigateByUrl() is used for absolute path navigation.

ie,

If we need to navigate to entirely different route in that case we can use router.navigateByUrl

For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()


Syntax :

router.navigateByUrl(' ---- String ----');

router.navigate([], {relativeTo: route})

Solution 5 - Angular

Let's say you're running your server on http://localhost:4200 and you're on http://localhost:4200/abc and under routing module you've defined path as below:

const appRoutes: Routes = [
{ path: 'abc', component: MainComponent, children: [
    {path: '', component: InitialComponent},
    {path: 'new', component: LoadedComponent}
]}]

Now, we'll import Router as below from @angular/router and assign it to any variable inside constructor(here myRoute).

import { Router } from '@angular/router';
constructor(private myRoute: Router) { }

Inside your method now you'll redirect using navigateByUrl which mean that if you're on http://localhost:4200/abc and trying to redirect using navigateByUrl to http://localhost:4200/abc/new you'll be able to i.e. it will first try to match the appRoutes config and once found in children it will redirect to LoadedComponent.Code is as below:

this.myRoute.navigateByUrl('abc/new');

Also, if we use navigate then it will work based on the activatedRoute and it has small change with current active route:

import { ActivatedRoute, Router } from '@angular/router';
constructor(private myRoute: Router, private activeRoute: ActivatedRoute) { }

Here, if I'm at http://localhost:4200/abc and I have a method call to navigate it to new route then it will be triggered based on the current active route and if it has new as Child Route then it will redirect to http://localhost:4200/abc/new

this.myRoute.navigate(['new'], {relativeTo: this.activeRoute});

Solution 6 - Angular

I faced the same issue. My solution:

...
<p @click=parseHTML v-html=data.html></p>
...
methods: {
  parseHTML(event) {
    if (event.target.href) {
      event.preventDefault();
      if (event.target.href.includes(location.hostname)) {
        this.$router.push(event.target.href)
      }
    }
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - AngularMax KoretskyiView Answer on Stackoverflow
Solution 2 - AngularEugene KulabuhovView Answer on Stackoverflow
Solution 3 - AngularSplaktarView Answer on Stackoverflow
Solution 4 - AngularJyothiView Answer on Stackoverflow
Solution 5 - Angularsid7747View Answer on Stackoverflow
Solution 6 - AngularМихаил ДокучаевView Answer on Stackoverflow