0

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?

1
  • You can use the factory design pattern. you can return the component from that factory by using the string value. Commented Jul 1, 2019 at 18:59

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I have seen something similar. That's plan B if nothing more advance turns up. Thank you!
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.