如何在angular2中使用@Directive处理点击事件?

Rol*_*ndo 11 angular

是否可以将click事件附加到指令上或指令内的元素?(不是组件)例如..我有一个如下定义的指令:

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

}
Run Code Online (Sandbox Code Playgroud)

在我使用该指令的html中(index.html,请注意我没有与@directive本身关联的任何模板,我可以包含点击事件吗?:

<div gridStack>
<div><a (click)="clickEvent()">Click Here</a></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我知道如果它是一个组件,这是有效的,但我希望尝试让它使用指令,如果可能的话.

Gar*_*son 37

您可以通过HostListener指令定义中的装饰器附加到click事件.例如:

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

请参阅此处的Angular文档

还有一些关于这个问题的信息

  • 但这将是主持人(指令所适用的元素),而不是儿童元素...你如何听儿童?(比如在他的情况下?或想象有2 ... <div gridStack> <a(click)= clickEvent1()">点击这里1 </a> <a(click)= clickEvent2()">点击这里2 </a> </ div>)? (7认同)