Within angular 18, I've organized my components in a directory named typeForm
. Each of these components displays a unique view, and my goal is to link each path to its corresponding component dynamically. Here's an example of what I'm aiming for:
// app.routes.ts
import { Routes } from '@angular/router';
import { FormComponent } from './form/form.component';
import { authGuard } from '../app/auth.guard';
import * as allComponents from './typeForm/*';
export const routes: Routes = [
{ path: '', redirectTo: '/form', pathMatch: 'full' },
{ path: 'form', component: FormComponent, canActivate: [authGuard] }
];
async function loadDynamicRoutes() {
for (const key of allComponents) {
routes.push({
path: allComponents.componentName,
component: allComponents.componentType,
canActivate: [authGuard]
});
}
}
loadDynamicRoutes();
Although the code above is incorrect, I am unsure of how to accomplish this task without manually declaring paths and importing individual components. Is there an alternative approach that would simplify this process?