I developed an app that showcases various visualizations of RxJS operators such as rx-map
, rx-filter
, rx-reduce
, and more. The visualizations function correctly on their own. Now, I am looking to enable users to select which visualization they want to view using routing. While I could create a separate route for each component, there are numerous components, making manual routing cumbersome.
I am experimenting with Angular's ComponentFactoryResolver
to achieve this functionality. Here is an example of how I implemented it:
@Component({
selector: 'rx-visualizations-app',
template: '<ng-template #container></ng-template>',
})
export class RxVisualizationsAppComponent implements OnInit, OnDestroy {
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
private componentRef: ComponentRef<{}>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit() {
const factory = this.componentFactoryResolver.resolveComponentFactory(
getComponentFromRoute(),
);
this.componentRef = this.container.createComponent(factory);
}
}
While this method successfully displays the component, it requires a comprehensive list of component routes and names, along with individual imports for each component, like:
switch (route) {
case 'map': return RxMapComponent
Although functional, this approach is not significantly less labor-intensive than creating a separate route for each visualization.
Is there a more efficient way to dynamically create components based on a selector or compile a template string within the app?