如何在angular2中使用@Directive处理点击事件?
发布时间:2020-12-17 06:56:47 所属栏目:安全 来源:网络整理
导读:是否可以将click事件附加到指令上或指令内的元素? (不是组件)例如..我有一个如下定义的指令: import { Directive,OnInit,Input,ElementRef,Renderer } from '@angular/core';declare var $: any; // JQuery@Directive({ selector: '[gridStack]'})export c
是否可以将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); } } 在我使用该指令的html中(index.html,请注意我没有与@directive本身关联的任何模板,我可以包含点击事件吗?: <div gridStack> <div><a (click)="clickEvent()">Click Here</a></div> </div> 我知道如果它是一个组件,这是有效的,但我希望尝试让它使用指令,如果可能的话. 解决方法
您可以通过指令定义中的HostListener装饰器附加到click事件.
@HostListener('click',['$event']) onClick($event){ console.info('clicked: ' + $event); } 请参阅Angular docs here 以及this question的更多信息 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 读书笔记 <Bootstrap Yourself with Linux USB Stack>
- 基于yum或apt的linux的bash测试
- vim – 更改snipMate中的默认选项卡
- angularjs – 我将如何将ui路由器转到外部链接,如google.co
- linux系统(CentOS 6.8)下安装PhantomJS
- 异步管道在Angular的输入中不起作用
- bash – 如何在qsub中指定错误日志文件和输出文件
- 一系列Bootstrap导航条使用方法分享
- angular – 使用x-www-form-urlencoded的HttpClient POST请
- bash – 在Vagrant上找不到来源
推荐文章
站长推荐
热点阅读