Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I navigate to a sibling route?

Let's presume I got this router config

export const EmployeeRoutes = [    { path: 'sales', component: SalesComponent },    { path: 'contacts', component: ContactsComponent } ]; 

and have navigated to the SalesComponent via this URL

/department/7/employees/45/sales 

Now I'd like to go to contacts, but as I don't have all the parameters for an absolute route (e.g. the department ID, 7 in the above example) I'd prefer to get there using a relative link, e.g.

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

or

this.router.navigate('../contacts') 

which unfortunately doesn't work. There may be an obvious solution but I'm not seeing it. Can anyone help out here please?

like image 572
Thorsten Westheider Avatar asked Jul 28 '16 10:07

Thorsten Westheider


People also ask

What is relative route in angular?

So by the use of relative path you are making your links free that are relative to the current URL segment. Your feature area of routing will be the same even if you change the route for the parent. You are just making your link free even if you change the parent route path. Prerequisites. HTML, CSS and JS.


1 Answers

If you are using the new router (3.0.0-beta2), you can use the ActivatedRoute to navigate to relative path as follow:

constructor(private router: Router, private r:ActivatedRoute) {}   /// // DOES NOT WORK SEE UPDATE goToContact() {   this.router.navigate(["../contacts"], { relativeTo: this.r }); } 

Update 08/02/2019 Angular 7.1.0

current route: /department/7/employees/45/sales

the old version will do: /department/7/employees/45/sales/contacts

As per @KCarnaille's comment the above does not work with the latest Router. The new way is to add .parent to this.r so

    // Working(08/02/2019)      // DOES NOT WORK SEE UPDATE     goToContact() {        this.router.navigate(["../contacts"], { relativeTo: this.r.parent });     } 

the update will do: /department/7/employees/45/contacts

Update 12/12/2021 Angular > 10

As @ziz194 mention it, this is how it now works.

constructor(private router: Router, private r:ActivatedRoute) {}   goToContact() {   this.router.navigate(["contacts"], { relativeTo: this.r }); } 
like image 51
Harry Ninh Avatar answered Oct 04 '22 22:10

Harry Ninh