首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用@Directive处理点击事件?

如何使用@Directive处理点击事件?
EN

Stack Overflow用户
提问于 2017-02-01 06:52:43
回答 1查看 35.1K关注 0票数 26

是否可以将click事件附加到@Directive (而不是@Component)上或内部的元素?

例如,我有一个定义如下的@Directive

代码语言:javascript
复制
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);
    }

}

在我使用该@Directive (在index.html中)的超文本标记语言中,请注意,我没有任何与@Directive本身相关联的模板,我可以包含click事件吗?:

代码语言:javascript
复制
<div gridStack>
    <div><a (click)="clickEvent()">Click Here</a></div>
</div>

我知道这工作,如果它是一个@Component,但我希望尝试让它与一个@Directive,如果可能的话。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-01 11:41:49

您可以在指令定义中通过HostListener装饰器附加到单击事件。例如:

代码语言:javascript
复制
@Directive({ selector: '[coolBehavior]' })
export class CoolBehaviorDirective {
    @HostListener('click', ['$event']) onClick($event){
        console.info('clicked: ' + $event);
    }
}

请参阅Angular文档here

有关更多信息,请访问this question

票数 68
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41968974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档