7

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?

PCK
  • 1,254
  • 6
  • 20
  • 37

2 Answers2

9

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

More about relative navigation:
https://stackoverflow.com/a/38808116/1356669
https://angular.io/guide/router#relative-navigation

isherwood
  • 58,414
  • 16
  • 114
  • 157
be4code
  • 688
  • 4
  • 15
  • 1
    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? – PCK Aug 09 '17 at 07:18
  • 1
    why does it not working? ```[routerLink]="['../new-contract']"``` – Andryxa Piddubnjak Jun 11 '20 at 11:36
  • @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. – be4code Jun 12 '20 at 05:11
1

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>
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70