Search code examples
angularangular2-routing

Load nested routes in same router-outlet


I have an Angular 4 application and my private.component.html something like this:

<app-breadcrumb></app-breadcrumb>
<router-outlet></router-outlet>

And my routing:

const privateRoutes: Routes = [
    {
        path: '',
        component: PrivateComponent,
        children: [
            {
                path: 'dashboard',
                component: DashboardComponent
            },
            {
                path: 'settings',
                component: SettingsComponent
            },
            {
                path: 'companies',
                component: CompaniesComponent,
                children: [
                    {
                        path: 'add',
                        component: FormCompanyComponent
                    },
                    {
                        path: ':id',
                        component: CompanyComponent
                    }
                ]
            }
        ]
    }
];

All components on first level is rendered in router-outlet of PrivateComponent. But I want (if possible) all other child (and I can have multiple levels), like /companies/add or /companies/20 still rendered in the same router-outlet of my private template. My actual code, sure, expect I have the outlet inside the companies.component.html.

This is important to implement my breadcrumb component and write "Home > Companies > Apple Inc.", for example.

It's possible create some structure like that?


Solution

  • Adding to @Karsten's answer, basically what you want is to have a componentless route and the empty path as the default component such as this:

    const privateRoutes: Routes = [
        path: 'companies',
        data: {
            breadcrumb: 'Companies'
        }
        children: [{
                path: '', //url: .../companies
                component: CompaniesComponent,
            } {
                path: 'add', //url: .../companies/add
                component: FormCompanyComponent,
                data: {
                    breadcrumb: 'Add Company' //This will be "Companies > Add Company"
                }
            }, {
                path: ':id', //url: .../companies/5
                component: CompanyComponent
                data: {
                    breadcrumb: 'Company Details' //This will be "Companies > Company Details"
                }
            }
        ]
    ];
    

    You will need to modify the breadcrumb dynamically to change "Company Details" with the actual company name.