41

Is it possible to attach click events to the element on or within a @Directive (not @Component)?

For example, I have a @Directive defined as follows:

import { Directive, OnInit, Input, ElementRef, Renderer } from '@angular/core';
declare var $: any; // JQuery

@Directive({
    selector: '[gridStack]'
})
export class GridStackDirective implements OnInit {
    @Input() w: number;
    @Input() animate: boolean;

    constructor(
        private el: ElementRef,
        private renderer: Renderer
    ) {
        renderer.setElementAttribute(el.nativeElement, "class", "grid-stack");
    }

    ngOnInit() {
        let renderer = this.renderer;
        let nativeElement = this.el.nativeElement;
        let animate: string = this.animate ? "yes" : "no";

        renderer.setElementAttribute(nativeElement, "data-gs-width", String(this.w));
        if(animate == "yes") {
            renderer.setElementAttribute(nativeElement, "data-gs-animate", animate);
        }

        let options = {
            cellHeight: 80,
            verticalMargin: 10
        };

        // TODO: listen to an event here instead of just waiting for the time to expire
        setTimeout(function () {
            $('.grid-stack').gridstack(options);
        }, 300);
    }

}

In the HTML, where I use that @Directive (in index.html), note that I do not have any template associated with the @Directive itself, can I include a click event?:

<div gridStack>
    <div><a (click)="clickEvent()">Click Here</a></div>
</div>

I know this works if it is a @Component, but am looking to try to get it working with a @Directive if it is possible.

0

1 Answer 1

87

You can attach to the click event via HostListener decorator in your directive definition. For example:

@Directive({ selector: '[coolBehavior]' })
export class CoolBehaviorDirective {
    @HostListener('click', ['$event']) onClick($event){
        console.info('clicked: ' + $event);
    }
}

See the Angular docs here

And some more info in this question

Sign up to request clarification or add additional context in comments.

1 Comment

But this would be for the host (the element the directive is applied to) but not for the children elements... how do you listen to children? (like in his case? or imagine having 2...<div gridStack> <a (click)="clickEvent1()">Click Here 1</a> <a (click)="clickEvent2()">Click Here 2</a> </div>) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.