I have this in my app-routing.module.ts:
const routes: Routes = [
{
path: 'login',
loadChildren: () => import('./pages/login/login.module').then((m) => m.LoginPageModule),
},
{
path: 'home',
loadChildren: () => import('./pages/home/home.module').then((m) => m.HomePageModule),
canLoad: [AuthGuard],
},
{
path: '**',
redirectTo: 'home',
pathMatch: 'full',
},
];
In my home-routing.module I have the following:
const routes: Routes = [
{
path: 'create-bet',
component: CreateBetComponent,
children: [{ path: 'bet-duration-select', component: BetDurationSelectComponent }],
},
{
path: '',
component: HomeComponent,
pathMatch: 'full',
},
{ path: '*', redirectTo: '' },
];
When I am on the home component ('[...]/home') I have a button that I want to use to navigate to '/create-bet'. I was expecting doing something like this would work:
this.router.navigateByUrl('/create-bet');
But this just redirects me back to '/home'. However if I change the path to
this.router.navigateByUrl('/home/create-bet');
I am correctly redirected to that URL and the component is shown. Why is it that I have to specify 'home' in the path?
Furthermore, on the create-bet Page, I have a button that I want to use to navigate to its child page ('bet-duration-select') like so:
this.router.navigateByUrl('/bet-duration-select');
Again, I was expecting this to work however, it redirects me back to the '/home' URL. Even if I specify the route as
this.router.navigateByUrl('/home/create-bet/bet-duration-select');
or
this.router.navigateByUrl('/create-bet/bet-duration-select');
I am always redirected back to '/home'.
Can someone explain to me why that behavior is happenning? I thought the way I had it set up should work... Even if I type out the url in the nav bar directly'[...]/home/create-bet/bet-duration-select' the 'create-bet' component is shown, instead of the bet-duration-select. What is going on here?
{
path: '**',
redirectTo: 'home',
pathMatch: 'full',
}
path '**' means 'any URL', so when Angular can't find specified URL, it redirects you to '/home'. Usualy this route is using for 404 page.
this.router.navigateByUrl('/home/create-bet/bet-duration-select');
because BetDurationSelectComponent
is a child component of CreateBetComponent
and grandchild of HomeComponent
. The routes in Angular app looks like a tree, so you have something like this:
/ <-- root
∟ home
∟ create-bet
∟ bet-duration-select
∟ login
You can also use relative paths if you want to navigate between neighbour components.
More info here: https://angular.io/guide/router