0

I'm trying to create format feature in angular where the format name is passed to a format child component. This format component is created via

let componentFactory = componentFactoryResolver.resolveComponentFactory(typeOfFormatComponent);

So, to make it configurable I need to pass the typeOfFormatComponent as a string - say - 'AddressFormatComponent'.

How do I turn the string 'AddressFormatComponent' into the type AddressFormatComponent for the resolveComponentFactory call?

Craig
  • 517
  • 1
  • 9
  • 17
  • 1
    Something like `const entryComponents = { 'AddressFormatComponent': AddressFormatComponent, ... `? – yurzui Mar 11 '18 at 15:40
  • Ideally, the parent compent does not know about any formatters (otherwise has to be changed when a new format is introduced to add it to the entryComponents). Hence the parent component only gets the type name as a string. – Craig Mar 11 '18 at 15:44
  • 1
    this could help https://stackoverflow.com/questions/40528592/ng2-dynamically-creating-a-component-based-on-a-template/40662376#40662376 – David Gabrichidze Mar 11 '18 at 17:58

1 Answers1

0

You can declare an interface for all FormatComponents:

interface FormatComponents {
    AddressFormatComponent: FormatComponent;
    ...
}
resolveComponentFactory(component: keyof FormatComponents) {
    let formatComponent = FormatComponents[component]; // This will work and be typed correctly.
}

This allows you to have compile time checking of types by enforcing that the stings match.

nileshp87
  • 25
  • 1
  • 6