Search code examples
angularangular8angular-componentsangular-router

Angular Route Params issue


I have a couple of routes like below. My main/base app-routing looks like below:

const routes: Routes = [{
    path: 'projects',
    loadChildren: () => import('../app/pages/pages.module').then(m => m.PagesModule)
}]

The PagesModule's Routing looks like below:

const routes: Routes = [
    {
        path: ':projectId/model', component: ModelComponent
    },
    {
        path: ':projectId/compare/:id', component: CompareComponent
    }
    {
        path: ':projectId/serving/:id', component: ServingComponent
    }
]

For Model component the url is correct, viz: localhost:4200/projects/123/model

With 123 as :projectId and 1 as :id, I want the URL for ServingComponent and CompareComponent be like: localhost:4200/projects/123/serving/1 localhost:4200/projects/123/compare/1

What works: navigation via HTML works like:

 <button [routerLink]="['../compare', model.id]">Compare</button>

Issue: When I navigate from my TS file it doesn't work. Tried with below:

 this.router.navigate(['../compare', model.id]);

Can you please suggest what can be wrong? Do I need to modify my routes ? I wonder why TS navigation is not working while navigation works from HTML. Please advice.


Solution

  • If you want to use relative path, you need to add relativeTo attribute like this: this.router.navigate(['../compare'], {relativeTo: this.activatedRoute}); (add also model.id param)

    More details: https://angular.io/guide/router#specifying-a-relative-route