Issue
I’m trying to declare a "dynamic" route component in angular.
This is my module
const routes: Routes = [
{
path: ':machine', component: LayoutComponent,
children: [
{
path: '', component: (() => {
return IsServerCondition ? MonitoringServerComponent : MonitoringClientComponent;
})()
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class MonitoringRoutingModule { }
I would like to change the component to be displayed based on the argument :machine of the parent path route. How can I do it?
Solution
In case you already know the predefined values of the parameter :machine you could use static routing to map to each component
In case you need to make a network request, you could certainly use a "dummy" component that makes the network request and later based on a response from the backend *ngIf or *ngSwitch
to see which component to load.
template
<app-client-component *ngIf="serverCondition$ | async; else server"></app-client-component>
<ng-template #server>
<app-server-component></app-server-component>
</ng-template>
typescript
@Component({…})
export class DummyComponent implements OnInit {
serverCondition$ = this.actRoute.paramMap.pipe(
// for direct comparison
map(params => param.get('machine') === 'red')
// or for a network request result
switchMap(params => this.service.checkBackend(param.get('machine'))),
map(response => response === 'red')
);
constructor(
private actRoute: ActivatedRouteSnapshot,
private service: BackendService
) {}
}