Reputation: 93
I have an issue navigating to a child component from the parent.
My app-routing is look like this:
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'parent',
component: ParentComponent,
children: [{
path: 'child',
component: ChildComponent
}]
},
{
path: '404',
component: PageNotFoundComponent
},
{
path: '**',
redirectTo: '404'
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
providers: [{
provide: APP_BASE_HREF,
useValue: '/'
}],
exports: [
RouterModule
],
})
export class AppRoutingModule {
}
and in the parent component I call this to navigate to the child on a button click:
this.router.navigate(['child', { relativeTo: this.route }]);
but I end up in 404 page instead.
What am I missing here?
Upvotes: 0
Views: 3346
Reputation: 3976
Check this stackblitz POC where I have used your routing configuration to redirect to child component
To redirect from parent I used following code -
public showChild(): void {
this._Router.navigate(['child'], {
relativeTo: this._ActivatedRoute
})
}
To redirect from root component. I used following code -
public showChild(): void {
this._Router.navigate(['parent', 'child'], {
relativeTo: this._ActivatedRoute
})
}
EDIT - Relative Approach
To have relative route use following code -
public showChild(): void {
this._Router.navigate(['./child'], {
relativeTo: this._ActivatedRoute
})
}
So if you want to go to parent route's siblings child
e.g. /parent1/child
from /parent
we would have used ../parent1/child
Upvotes: 1
Reputation: 1274
Try this
this.router.navigate(['../child'], { relativeTo: this.route });
According to The documentation your are missing two dots
You can read about it here (Angular NavigationExtras)
Upvotes: 4