Search code examples
angulartypescriptangular7

Convert string to class typescript/angular


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?


Solution

  • 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