Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 can't navigating relative to parent route

I use angular2 cli .

test navigating relative met problems:

routing config:

{
    path: '',
    component: CheckCompanyComponent,
    children:[
      {
        path:'',
        loadChildren: 'app/components/company/check-company-home/check-company-home.module#CheckCompanyHomeModule'
      },
      {
        path:':id',
        loadChildren: 'app/components/company/check-company-detail/check-company-detail.module#CheckCompanyDetailModule'
      }
    ]
  }

In check-company-home component

goIdPage(){
    this.router.navigate(['22'], { relativeTo: this.route });
  }

can navigate from "/company" to "/company/22"

In check-company-detail component:

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

But can't navigate form "/company/22" to "/company",

why?

like image 345
Kery Hu Avatar asked Nov 03 '16 07:11

Kery Hu


People also ask

How do you navigate to a parent route from a child route?

Directly using the routerLink directive in case of linkage of child to parent. Using Route class in case of navigation to happen on a triggered event.

What is relative navigation in angular?

While building the application with the use of absolute path we pin the same link everywhere we required that path. So when we change the parent route then we have to change the path to the links used outside also. So by the use of relative path you are making your links free that are relative to current URL segment.

How do you navigate using a router?

navigate method, you must supply the ActivatedRoute to give the router knowledge of where you are in the current route tree. After the link parameters array, add an object with a relativeTo property set to the ActivatedRoute . The router then calculates the target URL based on the active route's location.

How does router navigate work?

Angular router traverses the URL tree and matches the URL segments against the paths configured in the router configuration. If a URL segment matches the path of a route, the route's child routes are matched against the remaining URL segments until all URL segments are matched.


1 Answers

It works when I set relativeTo: this.route.parent and use single dot ['./'].

goBack(){
    this.router.navigate(['./'], { relativeTo: this.route.parent });
}
like image 87
Ricardo Valente Avatar answered Oct 05 '22 08:10

Ricardo Valente