How can I use relativeTo property in html template along with routerActive?
Asked Answered
Q

2

9

I need to use 'relativeTo' property as well as 'routerLinkActive' directive in my application. Having a click listener function that routes using

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

would be okay. But in that case I cannot use the routerLinkActive directive.

How can I simultaneously use both?

Queenie answered 9/8, 2017 at 3:42 Comment(4)
what is routerLinkActive option?Lamarckian
routerLinkActive is used to style the link when that particular path is active.Queenie
I know know, but it's a directive, not an option. So your question if confusingLamarckian
Sorry, my bad! Wrong usage of terms.Queenie
A
9

RelativeTo is by default set to currently activated route. In template you can use . or ^ in route name.

More about relative navigation:
https://mcmap.net/q/242666/-how-do-i-navigate-to-a-sibling-route
https://angular.io/guide/router#relative-navigation

Avar answered 9/8, 2017 at 5:20 Comment(3)
this.router.navigate(['grid'],{relativeTo:this.route,queryParamsHandling:'preserve'}); How can I do this in HTML template, since I also need to use routerLinkActive option to style the links?Queenie
why does it not working? [routerLink]="['../new-contract']"Egestion
@AndryxaPiddubnjak there is a lot of variables that make it hard to say why it does not working. You must keep in mind that link is created as relative but from the point where the component was rendered. Open new question because it's different issue, please.Avar
B
2

While the accepted answer works for the specific circumstance in the OP's example, it's not entirely correct (Also I have no idea what ^ is - that might be plain wrong or obsolete).

The RouterLink directive has many inputs, one of which is relativeTo. It works just like router.navigate's relativeTo option, allowing an ActivatedRoute to be passed.

A useful case for this is if you have a variable number of route parameters, and you want to be sure you're going back to parent. In the code below, route is the ActivatedRoute injected into a component. The link will safely go back up to the parent.

<a [routerLink]="'.'" [relativeTo]="route.parent">To Parent</a>
Bartholemy answered 11/3, 2023 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.