如何传递在angular2/4中单击的dom元素?
我有以下指示:如何传递在angular2/4中单击的dom元素?,angular,Angular,我有以下指示: import {Directive, HostListener, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[long-press]' }) export class LongPressDirective { private touchTimeout: any; @Output() longpress = new EventEmitter(); private roo
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);
}
}
我这样使用这个指令:
//<ion-item (click)="open(item)" long-press (longpress)="select(item)"></ion-item>
//
问题是,我想将实际引用传递给dom元素。通常通过(click)指令,我可以执行如下操作:
(click)=“somefunc($event)”
。使用我的指令,我想执行(longpress)=“选择($event,item)
”。我需要它,以便可以向dom添加属性。(内容可编辑)。如何修改long-press指令以传入$event,就像我已经可以使用(单击)开箱即用一样?您可以像这样将$event注入HostListener:
@HostListener('touchstart', ['$event']) {...}
下面是一个例子:
从“@angular/core”导入{Component,NgModule,HostListener,Directive,EventEmitter,Output}
从“@angular/platform browser”导入{BrowserModule}
@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 {
}
@指令({
选择器:“[myDir]”
})
导出类MyDir{
@Output()myDir=neweventemitter();
@HostListener('click',['$event'])onClick($event){
this.myDir.emit($event);
}
}
@组成部分({
选择器:“我的应用程序”,
模板:`
你好
`,
})
导出类应用程序{
构造函数(){
}
点击($event){
console.log($event);
}
}
@NGD模块({
导入:[BrowserModule],
声明:[App,MyDir],
引导:[应用程序]
})
导出类AppModule{
}
您能展示一下。。。部分我还是一无所获。即使我添加了那个和(longpress)=“选择($event,item)”