Search code examples
angularangular6angular7angular7-router

How to navigate to a child route by default - Angular 7 (Routes)


I am using Angular routes, to navigate through the components. When a user is logged in they are navigated to dashboard/:id and then they see dashboard/123/projects etc. The problem is, when the user navigates to /dashboard only, I want to redirect them to /dashboard/:id by default. But when I do it like this : { path:"dashboard", redirectTo:"dashboard/:id/projects", pathMatch:"full"} it through an error saying :id not defined, and I am unable to navigate to from /dashboard to the current user logged in /dashboard/123/projects.

My Routes.modules.ts code

const routes: Routes = [{
    path: "",
    redirectTo: "/login",
    pathMatch: "full"
  },
  {
    path: "login",
    component: LoginComponent
  },
  {
    path: "register",
    component: RegisterComponent
  },
  //the problem goes here
  {
    path: "dashboard",
    redirectTo: "", //How to redirect to dashboard/:id ?
    pathMatch: "full"
  },
  {
    path: "dashboard/:id",
    component: DashboardComponent,
    children: [{
        path: "",
        redirectTo: "projects",
        pathMatch: "full"
      },
      {
        path: "projects",
        component: ProjectsComponent
      },
      {
        path: "archived",
        component: ArchivedProjectsComponent
      },
      {
        path: "projects/:id",
        component: SingleProjectComponent,
        children: [{
            path: "",
            redirectTo: "plans",
            pathMatch: "full"
          },
          {
            path: "plans",
            component: PlansComponent
          },
          {
            path: "tasks",
            component: TasksComponent
          },
          {
            path: "photos",
            component: PhotosComponent
          },
          {
            path: "files",
            component: FilesComponent
          },
          {
            path: "people",
            component: PeopleComponent
          },
          {
            path: "settings",
            component: SettingsComponent
          },
          {
            path: "trash",
            component: TrashComponent
          },
          {
            path: "**",
            redirectTo: "plans",
            pathMatch: "full"
          }
        ]
      },
      {
        path: "**",
        redirectTo: "projects",
        pathMatch: "full"
      }
    ]
  },
  {
    path: "**",
    component: PageNotFoundComponent
  },
];


Solution

  • You can achieve this with your Login component. Redirect user to the child route once they are successfully logged in.

    Get the id of the user from the payload or from your API call depends on your structure, and pass it to the route.

    this.router.navigate(['/dashboard/' + id + '/projects']);
    

    this.router is an instance of Router.