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)?
Using RouterLink DirectiveRouterLink directive has support of ActivatedRoute automatically for relative navigation. We can use relative path and absolute path both with RouterLink directive.
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 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.
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.
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With