Enzio
Enzio

Reputation: 889

Angular : Routing to child component with navigate method with a relative route does not work

Example used is given in this stackblitz

This is how routing is structured

    RouterModule.forRoot([
      {
        path: 'login',
        component: LoginViewComponent,
        children: [
          { path: 'home', component: HomeViewComponent },
          { path: 'catalog/:id', component: CatalogViewComponent }
        ]
      },
      { path: '**', redirectTo: 'login' }
    ])
  ],

When I am in the login component, I can go to home component with this absolute route

this.navigate(['login/home']);

I can also use navigateByUrl() like this

this.navigateByUrl(['login/home']);

But I don't understand how to route relatively with navigate()

this.navigate(['home'], { relativeTo: this.route });
this.navigate(['/home'], { relativeTo: this.route });

None of these methods are routing to homeComponent

Upvotes: 3

Views: 4111

Answers (1)

xinthose
xinthose

Reputation: 3820

Instead of making child routes, I just have another route with the same name in the path:

app-routing.module.ts

{ path: "activity", component: ActivityComponent },
{ path: "activity/orders", component: OrdersComponent },

If I am in the activity component, I navigate to orders by:

this.router.navigate(["orders"], { relativeTo: this.route });`

import and constructor in the activity component

import { Router, ActivatedRoute } from "@angular/router";
constructor(
  private router: Router,
  private route: ActivatedRoute,
) {

Upvotes: 2

Related Questions