Search code examples
javascriptangulartypescriptannotationsangular5

Angular - How to access annotation class method


I have the following declaration of a annotation in Angular:

class ModalContainer {
    public destroy: Function;
    public closeModal() {
        this.destroy();
    }
}

export function Modal() {
    return function (target: any) {
        Object.assign(target.prototype, ModalContainer.prototype);
    };
}

I want to use the annotation inside a component:

@Component({
    selector: 'my-component',
    templateUrl: 'my-component.template.html',
    styleUrls: ['my-component.style.scss']
})
@Modal()
export class MyComponent implements OnInit {
    private EVENT_SAVE = 'EVENT_SAVE';
    private EVENT_CANCEL = 'EVENT_CANCEL';
    private buttonClick(event: any, eventType: string){
        if (eventType === this.EVENT_CANCEL){
            this.closeModal();
        } else if(eventType === this.EVENT_SAVE){
            this.closeModal();
        }
    }
}

The problem is, TypeScript is not able to compile, since this method is not known during compile time. However, when I'm using the same method call inside the template, then it works. That means, that the the prototype was assigned.

The compiler shows this error message:

ERROR in [at-loader] ./src/main/webapp/ui/src/my-component.component.ts:128:18
    TS2339: Property 'closeModal' does not exist on type 'MyComponent'.

Does anyone know, how I cann solve this?


Solution

  • By adding this line the compiler will not complain anymore and it works.

    private closeModal: Function;
    

    The class then looks like this:

    @Component({
        selector: 'my-component',
        templateUrl: 'my-component.template.html',
        styleUrls: ['my-component.style.scss']
    })
    @Modal()
    export class MyComponent implements OnInit {
        private EVENT_SAVE = 'EVENT_SAVE';
        private EVENT_CANCEL = 'EVENT_CANCEL';
        private closeModal: Function;
        private buttonClick(event: any, eventType: string){
            if (eventType === this.EVENT_CANCEL){
                this.closeModal();
            } else if(eventType === this.EVENT_SAVE){
                this.closeModal();
            }
        }
    }