Nicolas Garin Nicolas Garin - 3 months ago 10
TypeScript Question

Change Annotations before sending component on Angular 2

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 :)

Answer

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 ;)

Comments