如何在angular 8中为viewchild元素引用编写单击事件

如何在angular 8中为viewchild元素引用编写单击事件,angular,Angular,在typescript中尝试了元素引用的单击事件,但不起作用。如何编写元素引用的单击事件。如果有人知道,请帮助找到解决方案 app.component.ts: @ViewChild('el') testElement: ElementRef; ngAfterViewInit() { this.testElement.nativeElement.onmouseenter = () => console.log('mouse enter') this.testElement.nat

在typescript中尝试了元素引用的单击事件,但不起作用。如何编写元素引用的单击事件。如果有人知道,请帮助找到解决方案

app.component.ts:

@ViewChild('el') testElement: ElementRef; 

ngAfterViewInit() {
  this.testElement.nativeElement.onmouseenter = () => console.log('mouse enter')
  this.testElement.nativeElement.onclick = () => console.log('clicked')
}
@ViewChild('testElem')el:ElementRef;
@ViewChild('testElem2')el2:ElementRef;
this.el.on('click',()=>{
警报(“测试”);
});
app.component.html:

<div #el>testElem</div>
testElem
测试员2

这样,您就不需要
@ViewChild
来编写单击事件

app.component.html

testElem
应用程序组件.ts

//类上的方法
onClick(){
log('element clicked');
警报(“测试”);
}

我强烈认为您不应该为此使用元素引用,但如果您确实必须:

@ViewChild('testElem')el:ElementRef;
恩戈尼尼特(){
this.el.nativeElement.on('click',()=>{
警报(“测试”);
});
}

这样,您就不需要
@ViewChild
来编写单击事件

app.component.html

testElem
应用程序组件.ts

//类上的方法
onClick(){
log('element clicked');
警报(“测试”);
}

我强烈认为您不应该为此使用元素引用,但如果您确实必须:

@ViewChild('testElem')el:ElementRef;
恩戈尼尼特(){
this.el.nativeElement.on('click',()=>{
警报(“测试”);
});
}

您可以制作如下内容:

app.component.html


您可以制作如下内容:

app.component.html


您现在可能已经解决了这个问题,但对于那些想知道

您的
elementRef
引用错误,应该调用
elementRef
nativeElement
属性上的事件函数

这应该起作用:

app.component.html:

<div #el>testElem</div>

也许你现在已经解决了,但是对于那些想知道

您的
elementRef
引用错误,应该调用
elementRef
nativeElement
属性上的事件函数

这应该起作用:

app.component.html:

<div #el>testElem</div>

请使用元素引用您不应该为此使用元素引用。。你想做什么?请使用元素引用你不应该为此使用元素引用。。你想干什么?