1

I have a DashboardComponent that is being loaded if the router is at /client and the same for /product:

export const routes: Routes =
[
    { path: '', component: HomeComponent },
    { path: 'client', component: DashboardComponent },
    { path: 'product', component: DashboardComponent }

];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class RoutesModule { }

And I then load the different components in like this (in dashboard.component.ts):

this.router.events.subscribe(path => {

    if (this.router.url == "/client") {
        this.isClient = true;
    }

    if (this.router.url != "/client") {
        this.isClient = false;
    }
    if (this.router.url == "/product") {
        this.isProduct = true;
    }

    if (this.router.url != "/product") {
        this.isProduct = false;
    }

});

Then in the dashboard.component.html I do:

<app-client *ngIf="isClient"></app-client>
<app-product *ngIf="isProduct"></app-product>

I feel like this is not the way to do it but I cannot find a good explanation on how to implement that if you go to e.g. /dashboard/client it loads the ClientComponent inside of the DashboardComponent and the same for ProductComponent

1 Answer 1

2

You can accomplish this with child router-outlets

// routing.module.ts
export const routes: Routes = [
    { path: '', component: HomeComponent },
    {
        path: 'dashboard',
        component: DashboardComponent,
        children: [
            {
                path: 'client',
                component: ClientComponent
            },
            {
                path: 'product',
                component: ProductComponent
            }
        ]
    }
]

and add the child router outlet to your DashboardComponent

<div>
    dashboard component
    <router-outlet></router-outlet>
</div>

So when the user goes to /dashboard/client, DashboardComponent is loaded in the top level router-outlet, and ClientComponent is loaded into the child router-outlet (inside of DashboardComponent). Here is a stackblitz demoing this

Sign up to request clarification or add additional context in comments.

2 Comments

@MeesKluivers as a side note, I would add another route definition under DashboardComponent children: [{path: '', pathMatch: 'full', redirectTo: 'client'}] so when the user hits just /dashboard they are redirected to /dashboard/client. I've updated my stackblitz
Ah I see, what I did was add the path:‘’ and then load the ClientComponent. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.