首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何传递在angular2/4中单击的dom元素?

如何传递在angular2/4中单击的dom元素?
EN

Stack Overflow用户
提问于 2017-04-28 18:45:22
回答 1查看 938关注 0票数 0

我有以下指令:

代码语言:javascript
复制
import {Directive, HostListener, Output, EventEmitter} from '@angular/core';

@Directive({
  selector: '[long-press]'
})
export class LongPressDirective {
  private touchTimeout: any;
  @Output() longpress = new EventEmitter();

  private rootPage: any;

  constructor() {}

  @HostListener('touchstart') touchstart():void {
    this.touchTimeout = setTimeout(() => {
        this.longpress.emit({});
    }, 400);
  }

  @HostListener('touchend') touchend():void {
      this.touchEnd();
  }
  @HostListener('touchcancel') touchcancel():void {
      this.touchEnd();
  }

  private touchEnd():void {
    clearTimeout(this.touchTimeout);
  }
}

我使用这样的指令:

代码语言:javascript
复制
//<ion-item (click)="open(item)" long-press (longpress)="select(item)"></ion-item>

问题是,我想传递对dom元素的实际引用。通常使用(单击)指令,我可以执行类似于:(click)="somefunc($event)"的操作。使用我的指令,我想要做(longpress)="select($event, item)“。我需要这样做,这样我就可以向dom添加一个属性。(内容可编辑)。我如何修改我的长按指令以传递$event,就像我已经可以(单击)打开框一样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-28 18:49:09

您可以像这样将$event注入HostListener:

代码语言:javascript
复制
@HostListener('touchstart', ['$event']) {...}

下面是plunk:https://plnkr.co/edit/j852SpnyorLObg07qmo0

导入{组件、NgModule、HostListener、指令、EventEmitter、Output}从“@角/核心”导入{BrowserModule},从“@角/平台-浏览器”导入{BrowserModule}

代码语言:javascript
复制
@Directive({
  selector: '[myDir]'
})
export class MyDir {
  @Output() myDir = new EventEmitter<any>();

  @HostListener('click', ['$event']) onClick($event) {
    this.myDir.emit($event);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (myDir)="clicked($event)">hello</h2>
    </div>
  `,
})
export class App {
  constructor() {
  }

  clicked($event) {
    console.log($event);
  }
}

@NgModule({
  imports: [BrowserModule],
  declarations: [App, MyDir],
  bootstrap: [App]
})
export class AppModule {
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43686991

复制
相关文章

相似问题

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