Reputation: 4288
I have a component that is a modal popup. It takes a string as an input and then loads other components dynamically. That way I can have one modal popup component instead of replicating a modal popup code for every modal i need in the app. Problem is that this results in a large if/else statement where I load appropriate component based on the string input as such
if (this.data.component == "ContactStaffComponent")
componentFactory = this.componentFactoryResolver.resolveComponentFactory(ContactStaffComponent);
else if (this.data.component == "DocketComponent")
componentFactory = this.componentFactoryResolver.resolveComponentFactory(DocketComponent);
else if (this.data.component == "FilingComponent")
componentFactory = this.componentFactoryResolver.resolveComponentFactory(FilingComponent);
else if (this.data.component == "ServiceListRecordComponent")
componentFactory = this.componentFactoryResolver.resolveComponentFactory(ServiceListRecordComponent);
else { }
Is there a way to convert the string into type? Something along the lines of .net reflection?
Upvotes: 0
Views: 1507
Reputation: 810
To make the code more succinct, you can declare an Observable of Components in this way:
import { of } from 'rxjs';
import { filter } from 'rxjs/operators';
...
export class ... {
componentList$ = of(
ContactStaffComponent,
DocketComponent,
FilingComponent,
ServiceListRecordComponent
);
...
}
You can get the name of the component by accessing the .name attribute from componentList$. And filter the componentList$ as follows.
this.componentList$.pipe(
filter(component => this.data.component == component.name.toString()))
.subscribe((componentName: any) =>{
componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentName);
});
Hope this helps. CYA!
Upvotes: 0
Reputation: 749
You can create an object with your components
private modals = {
ContactStaffComponent: ContactStaffComponent,
DocketComponent: DocketComponent
};
Then based on the input string you can get the component and pass it to the component resolver
let component = this.modals[this.data.component];
componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
Through this, you can eliminate a large if/else code chunk. Hope this is helpful
Upvotes: 1