0

I'm developping an app on Angular 2 and in this app I need to change dynamically some attributes inside @Component decorator. Here is my code :

function componentFactory (directives: any[], template: string) {
    let annotations = Reflect.getMetadata('annotations', ComponentBase)
    annotations[0].directives = directives
    annotations[0].template = template

    let metadata = new ComponentMetadata(annotations)
    Reflect.defineMetadata('annotations', [ metadata ], ComponentBase)

    return ComponentBase
}

The problem is that when I use it (with a ComponentResolver) I get this error : "Component 'ComponentBase' must have either 'template' or 'templateUrl' set.".

Do you have any suggestions ?

Thank you :)

Nicolas Garin
  • 213
  • 3
  • 11
  • Why do you need to dynamically change some attributes. – Pablo Ivan Aug 24 '16 at 00:11
  • Thanks for your answer @pablo. I need to add directives in my component without knowing which ones I want to use. I've managed to make it work but this is not a good practice (declaring the same classe multiple times) : function componentFactory (directives: any[], template: string) { @Component({ directives: directives, template: template, }) class ComponentBase {} return ComponentBase } – Nicolas Garin Aug 24 '16 at 10:50
  • Maybe you could use the Component Router? – Pablo Ivan Aug 24 '16 at 22:31

1 Answers1

1

I've finally found how to create dynamic components

function createDynamicComponent<T extends IBase> (componentAttributes: any, SuperClass: IConstructor<T>) {
    class DynamicComponent extends (<IConstructor<IBase>> SuperClass) {}

    return Component(componentAttributes)(DynamicComponent)
}

interface IConstructor<T> {
    new (...args): T
}

interface IBase {}

I forgot that we can use decorators as functions ;)

Nicolas Garin
  • 213
  • 3
  • 11