简体   繁体   English

如何在 angular 中触发自定义事件

[英]how to fire custom event in angular

I have created custom event for mousestop, but i am not able to fire the component methods from the custom event.我已经为 mousestop 创建了自定义事件,但我无法从自定义事件中触发组件方法。 below is the html code下面是 html 代码

<div class="col-md-12 img-div" #imageCanvas>
            <img id="srcImg" #srcImg class="crf-img" (click)="createOverlay($event)"
                src="../../assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.blank_0.jpg">
</div>

below is the component.ts code.下面是 component.ts 代码。

ngOnInit() {
    (function (mouseStopDelay) {
      var timeout;
      document.getElementById('srcImg').addEventListener('mousemove', function (e) {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
          var event = new CustomEvent("mousestop", {
            detail: {
              clientX: e.clientX,
              clientY: e.clientY
            },
            bubbles: true,
            cancelable: true
          });
          e.target.dispatchEvent(event);
        }, mouseStopDelay);
      });
    }(2000));

    document.getElementById('srcImg').addEventListener('mousestop', function (e) {
      // console.log('You stopped your mouse while on the link');
      console.log('Mouse stopped and coordinates are: ', (e as any).detail.clientX, (e as any).detail.clientY);
      
        this.onMouseMove((e as any).detail.clientX, (e as any).detail.clientY);
    });
  }
  onMouseMove(x: number, y: number) {
    ----some code here--- 
  }

but i am getting below error但我得到低于错误

ERROR TypeError: this.onMouseMove is not a function
    at HTMLImageElement.<anonymous> (eimage.component.ts:75)

Kindly let me know how to resolve it.请让我知道如何解决它。 I have implemented same in ngAfterViewInit also but i am facing same error.我也在 ngAfterViewInit 中实现了相同但我面临同样的错误。

The problem is that you are using a function instead of an arrow function () => {} .问题是您使用的是function而不是箭头 function () => {} For that reason your this changes.因此,您的this发生了变化。 Change改变

document.getElementById('srcImg').addEventListener('mousestop', function (e) {

to

document.getElementById('srcImg').addEventListener('mousestop', (e) => {

Here you can find additional info on that topic.在这里您可以找到有关该主题的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM