I have created a project to illustrate my problem:
I have a parent component in which two child component should be visitable via link
<p>Child1 should be displayed by default at the start of the app</p>
<!-- <app-child1> </app-child1> -->
<a [routerLink]="['/child1']" routerLinkActive="router-link-active">Child1</a>
<a [routerLink]="['/child2']"> Child 2</a>
<router-outlet></router-outlet>
The problem is, that at the start of the application child1 component should be displayed by default but clicking on the link to child2 the content of child one should be gone. So only one of the child should be loaded at the time (router-outlet).
My routing-module
const routes: Routes = [
{path: '', component: ParentComponent, children: [
{path: 'child1', component: Child1Component},
{path: 'child2', component: Child2Component}
]}
];
How can I approach this problem with Angular routing or do I have to set some booleans and use *ngIf?
Add default child route component redirect:
const routes: Routes = [
{ path: '', component: ParentComponent, children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component },
{ path: '', redirectTo: '/child1', pathMatch: 'full' },
]}
];
and add another <router-outlet></router-outlet>
to your parent component. I created a STACKBLITZ to illustrate it. All components are in the same ts file for simlicity only.
You can read more at the official site.