Search code examples
javascriptangulartypescriptangular-routing

Angular router : how to redirect to a component based on a part of the routerlink


In my Angular app

i ve this routing file :

const routes: Routes = [
  {
    path: "",
    children: [
      {
        path: "",
        redirectTo: "/my-default-page",
        pathMatch: "full"
      },
      {
        path: "reset_password",
        component: ResetPassword,
        canActivate: [MyAuthGuard],
        children: [{ path: "**", redirectTo: "/reset_password" }]
      }
    ]
  }
}
];

i want to not pass by a redirection , and that when the route : would be soemthing like this :

/reset_password/blabalabla

it would not redirect me but simply load the component ResetPassword and keeps the url as it is

Suggestions ?


Solution

  • Use route parameters. You then don't need any children routes.

    {
        path: "reset_password/:id",
        component: ResetPassword,
        canActivate: [MyAuthGuard]
      }
    

    Your link will remain the same and if you want you can retrieve this parameter from the link using the following code in your ResetPassword component

    constructor(private route: ActivatedRoute){}
    
    ngOnInit():void{
    const id = this.route.snapshot.paramMap.get('id');
    }