Search code examples
angularangular-router

In Angular, how to navigate to a relative path with `href`?


I am using Ionic with Angular (i.e. and @angular/router), but I believe that this question is also relevant to Angular without Ionic.

How can I navigate to a relative folder using href?

I have this structure:

(root)
..A
....B1
....B2

When I navigate to /A/B1 - the B1 component is rendered. In it, I have this HTML:

<ios-button href="../B2">Click Me</ios-button>

I expect a button click to navigate to /A/B2, but instead, it navigates to /B2.

I also tried href="./../B2" but it gives the same result.

If I use the full path (href="/A/B2") then it works.

How do I achieve my expected result with the partial (i.e. relative) path?


Solution

  • You have an option to implement it like this, handling redirection inside your Component

    More info on Angular's specifying-a-relative-route documentation

    @Component({...})
    export class TestComponent {
    
       constructor(
          private router: Router
          private route: ActivatedRoute
       ) {}
    
       navigateTo(path: string): void {
           this.router.navigate([path], { relativeTo: this.route });        
       }
    }
    

    With this in place { relativeTo: this.route } and if you have a path ../B2, you're telling Angular that from this current route, go 1-step backward and go to B2

    Mock Parent Route: http://localhost:4200/parent

    Example #1

    // This will be http://localhost:4200/parent/B2
    this.router.navigate(['B2'], { relativeTo: this.route });
    

    Example #2

    // This will be http://localhost:4200/B2
    // As this goes up one level
    this.router.navigate(['../B2'], { relativeTo: this.route });
    

    NOTE:

    • When dealing with route redirection, it's best to use [routerLink]="" instead of href inside your template

      • Accessing levels up <a [routerLink]="[../B2]">B2</a>
      • If one level only, <a [routerLink]="'B2'">B2</a> with single quote inside
    • Or if you'll handle redirection in your component, you'll use Router from @angular/router


    Have created a Stackblitz Demo for your reference