如何在角度8中编写viewchild元素引用的点击事件

Nil*_*ani 3 angular

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

应用程序组件.ts:

@ViewChild('testElem') el:ElementRef;
@ViewChild('testElem2') el2:ElementRef; 

this.el.on('click',()=>{ 
  alert("test"); 
});
Run Code Online (Sandbox Code Playgroud)

应用程序组件.html:

<div #el>testElem</div>

<div #el2>testElem2</div>
Run Code Online (Sandbox Code Playgroud)

Ric*_*cky 7

你可以做这样的事情:

应用程序组件.html

<div #el">testElem</div>
Run Code Online (Sandbox Code Playgroud)

应用程序组件.ts

import { AfterViewInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'
import { fromEvent, Subscription } from 'rxjs';

@Component({
  selector: 'app-component',
  templateUrl: 'app.component.html'
})
export class AppComponent implements AfterViewInit {
  
  @ViewChild('el', { static: false}) el: ElementRef;

  clickedElement: Subscription = new Subscription();

  ngAfterViewInit() {
    this.clickedElement = fromEvent(this.el.nativeElement, 'click').subscribe(() => console.log('element clicked'));
  }

  ngOnDestroy() {
    // add this for performance reason
    this.clickedElement.unsubscribe();
  }
}
Run Code Online (Sandbox Code Playgroud)

我们使用AfterViewInitHook 是因为 DOM 已经存在。

我希望我能够帮助你。