0

In Angular, i get a String and want to transform it to a Type / Component. For example, i get "ListComponent" and want to add a ListComponent to the Application. I dont want to map these in an Map or something. Is it possible to get the Type out of a String?

stringComponent = "ListComponent";
typeComponent = *transform "ListComponent" to ListComponent;
method(typeComponent);
M. We
  • 13
  • 2
  • Does the component exist in your template? – vsarunov May 26 '19 at 13:43
  • `I dont want to map these in an Map` well you are stuck then aren't you. This question has been asked many times here and the answer is the same. There is no **string** representation for a component factory in the Angular API anywhere. Component factories have a string selector, but there is no way to get an array of all factories because they are bound to modules. Modules are a hierarchy but there is no way to get child modules from the application reference. So you're stuck. – Reactgular May 26 '19 at 14:13
  • @vsarunov yes, it exists. – M. We May 26 '19 at 14:18
  • @cgTag okay, yes i searched for it, but could not find any solution.. thanks for your answer. – M. We May 26 '19 at 14:19
  • https://stackoverflow.com/questions/38636553/create-component-from-a-string – Reactgular May 26 '19 at 14:24
  • thanks to your answer, I found this https://stackoverflow.com/questions/40115072/how-to-load-component-dynamically-using-component-name-in-angular2 which helped me a lot! Thank you! :) – M. We May 26 '19 at 15:38

1 Answers1

0

Maybe something like:

class ListComponent {
  foo = 'bar'
}
class LolComponent {}

const componentsMap = {
  ListComponent,
  LolComponent
}

type ComponentName = keyof typeof componentsMap;


function convertStringToComponent<Name extends ComponentName>(name: Name): (typeof componentsMap)[Name] {
  return componentsMap[name];
}

const CompByName = convertStringToComponent('ListComponent');

const instance = new CompByName();

instance.foo; // ok!
Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91