Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative links/partial routes with routerLink

In my app some URLs take the form

/department/:dep/employee/:emp/contacts 

In my sidebar I show a list of all employees, each of which has a [routerLink] which links to that employee's contacts

<ul>     <li>         <a [routerLink]="['/department', 1, 'employee', 1, 'contacts']"></a>     <li>     <li>         <a [routerLink]="['/department', 1, 'employee', 2, 'contacts']"></a>     <li>     ... </ul> 

However, with this approach I always need to provide the full path, including all the params (like dep in the above example) which is quite cumbersome. Is there a way to provide just part of the route, such as

<a [routerLink]="['employee', 2, 'contacts']"></a> 

(without the department part, because I don't really care about department in that view and my feeling is that this goes against separation of concerns anyway)?

like image 610
Thorsten Westheider Avatar asked Jul 05 '16 20:07

Thorsten Westheider


People also ask

Is routerLink relative?

Using RouterLink DirectiveRouterLink directive has support of ActivatedRoute automatically for relative navigation. We can use relative path and absolute path both with RouterLink directive.

What is correct about relative link paths 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.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.

What is difference between routerLink and href?

Href is the basic attribute provided by Html to navigate through pages which reloads the page on click. routerLink is the attribute provided by angular to navigate to different components without reloading the page.


2 Answers

That's supposed to work. The leading / makes it an absolute route, without it (or with ./), it becomes a relative route relative to the current route. You can also use ../ (or ../../ or more) to route relative to the parent or parents parent.

like image 123
Günter Zöchbauer Avatar answered Oct 02 '22 13:10

Günter Zöchbauer


Instead of using './' or '../', I would suggest using relativeTo param in router.navigate function. E.g.:

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

or

this.router.navigate(['sibling'], {relativeTo: this.route.parent}); 
like image 35
Terry Lam Avatar answered Oct 02 '22 13:10

Terry Lam