简体   繁体   中英

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

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

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

https://angular.io/api/router/RouterLink很好地概述了如何创建将用户带到Angular4中不同路径的链接,但是我找不到如何以编程方式执行相同的操作,而是需要用户单击链接

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 ie 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});

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)
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM