简体   繁体   中英

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?

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM