Troubleshooting the failure of the addEventListener mouseEvent in an Angular environment

Recently, I've been encountering an issue with adding addEventListener to dynamically created HTML canvas elements. Everything was working fine before, but now none of the events seem to be triggered. Below is the code snippet I am currently using:

this.canvas.addEventListener('mousedown', (event) => {...});

Is there another method available to register mouse/touch events for DOM elements?

Check out this Stackblitz example

Answer №1

Make sure you are able to access the this.canvas in your class. Here are some alternative methods: 1. One way is to use plain JavaScript, select the element by id and add an event listener to it.

// Add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", yourCustomCallBackFunction);

2. Another method is to create a directive and use it for your canvas, see example code below:

import { Directive, ElementRef, Renderer, HostListener } from '@angular/core';
@Directive({
selector: '[appChbgcolor]'
})
export class ChangeBgColorDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
    // this.ChangeBgColor('red');
}
@HostListener('mouseover') onMouseOver() {
    this.ChangeBgColor('red');
}
@HostListener('click') onClick() {
    window.alert('Host Element Clicked');
}
@HostListener('mouseleave') onMouseLeave() {
    this.ChangeBgColor('black');
}
ChangeBgColor(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement, 'color', color);
 }
}

Then, place the directive in your HTML like this:

<div appChbgcolor>
     <h3>{{title}}</h3>
</div>

Reference: Detailed description of hostListener in Angular

Answer №2

After some trial and error, I managed to get it functioning by adjusting the event listener to attach to the document itself rather than the canvas element.

document.addEventListener('mousedown', (event) => {
      console.log('mousedown called');
      event.preventDefault();
      this._setScratchPosition();
      document.addEventListener('mousemove', this.scratching);
      this.callbackFun();

Alternatively, you could also use:

window.addEventListener('mousedown', (event) => {
      console.log('mousedown called');
      event.preventDefault();
      this._setScratchPosition();
      window.addEventListener('mousemove', this.scratching);
      this.callbackFun();
    });

If you prefer a more specific approach, you can declare a new variable like so:

public c: any;

and then add:

this.c = document.getElementById('myCanvas');
    this.c.addEventListener('scratch.move', () => {
      this.percent = Number(this.getPercent().toFixed(2));
      console.log('scratch.move called');
      if (this.percent > 5) {
        this.togglePrizeLabel();
      }
    });

By following these adjustments, everything now functions as intended. It is important to note that direct referencing of a canvas object may not work as expected, as discussed in this Stack Overflow thread.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to access a document that has the lang attribute set to "en" using JavaScript?

I am working on implementing conditional styling in JavaScript by referencing this line of code located before the opening <head> and <body> tags: <html class="js" lang="en"> I want to set a condition so that if the l ...

utilizing routerLinks to transfer data and trigger a specific function

I'm having trouble passing data through the routerLink and calling the function(). It doesn't seem to be working as expected. Here's an example of my code and you can view a working demo on StackBlitz. First Component(HTML) <span [route ...

Revert Bootstrap 4 Sidebar to its Previous State Upon Navigating Back in the Browser with Recursive Expansion

Check out this HTML, CSS, Bootstrap 4 code that creates a collapsible sidebar menu with an accordion-style design: https://i.sstatic.net/2hPmd.png My Goal I want to achieve the following using either Bootstrap 4, jQuery, or JavaScript... If I click on ...

How can I incorporate a JavaScript module into my Typescript code when importing from Typeings?

Exploring Angular2 and Typescript with the help of mgechev's angular2-seed for a new project has been an interesting experience. However, I have encountered a problem along the way. My intention is to incorporate Numeral into a component, and here ar ...

What steps can I take to resolve the issue in my code? I keep receiving a type error stating that it cannot read

I seem to be encountering an issue when running my code where I receive a 'cannot read property 'age' of null'. This error breaks my code, and I'm trying to figure out how to implement a check to ensure it only runs when I am signe ...

The reference to a $scope array in AngularJS has not been properly updated

Check out the code snippet below: var myapp = angular.module('myapp', []); myapp.controller('FirstCtrl', function ($scope) { $scope.people = [ { id: 1, first: 'John', last: 'Rambo' }, { id: 2, first: 'R ...

Employ a variable in order to send json

Is it possible to insert data into a predefined JSON variable using a variable? Here are the predefined JSON variables: data(){ return { dataMON: [], dataTUE: [], dataWED: [], dataTHU: [], ...

What method does the browser use to identify angularjs tags within HTML documents?

When using the AngularJS framework in HTML, we incorporate "ng" into HTML tags. However, how does the browser identify or recognize the HTML tags with "ng"? I am seeking the correct solution to this question. ...

When using Angular 2's HTTP POST method, it initiates an OPTIONS request

I've come across a peculiar issue with my Angular 2 application. I'm trying to send a JSON via a POST call to my Play Scala API, but it keeps attempting to make an OPTIONS request. Below is the code snippet : LoginService constructor (private ...

Navigating the coordinates for iframe integration in angular js

Hey there! I've been working with Angular and attempting to integrate an iframe. I have tried various methods to insert the longitude and latitude values from the database, but every time I try to input something like this, I encounter an error. Her ...

Creating a nested type using template literal syntax

Given a two-level nested type with specific properties: export type SomeNested = { someProp: { someChild: string someOtherChild: string } someOtherProp: { someMoreChildren: string whatever: string else: string } } I am looking ...

Showing the Datepicker from jQuery right in the middle of the screen

Here's the generated code as default: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper- clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2" style="width: 34em; position: absolute; left: ...

Incorporating a script into Angular can only be done within the index.html file

Currently, I am faced with an issue while working with Angular 17. I am attempting to utilize a script for generating a form within a component. The script can be found at this source: https://sandbox.przelewy24.pl/inchtml/ajaxPayment/ajax.js?token={TOKEN} ...

Completely charting the dimensions of an unfamiliar object (and the most effective method for determining its extent)

I am facing a challenge with a "parent" object that contains an unknown number of children at various depths. My main objective is to efficiently map this "parent" object and all its levels of children. How can I achieve this task? Each child already inc ...

Chrome will automatically retry an AJAX POST request if it times out after 10 seconds

I am in the process of creating a React JavaScript application using a back end powered by Node.js and Express. The software versions being used are as follows: React: ^16.0.0 Node: v8.0.0 Express: ^4.14.0 Chrome: Version 63.0.3239.84 (Official Build) (64 ...

Timezones not synchronizing properly with Moment.js

Hello everyone, I am currently exploring the world of moment.js along with the timezone add-on. I'm encountering some issues with a world clock project that involves using moment.js and moment-timezone.js together on a page where highcharts are also p ...

IE is giving an "Access is denied" message when making an Ajax request

I have implemented an AJAX request to check the response of websites like this: $.ajax ({ url: 'https://www.example.com', cache: false, success : function() { alert(new Date() - start) }, }) This code fun ...

Evaluating text presence with Nightwatch and Selenium by checking for single quotes in an element

I need to verify if an element includes text with an apostrophe. I attempted: 'PROGRAMMA\'S' or "PROGRAMMA'S", such as .assert.containsText('element', 'PROGRAMMA\'S') However, neither method seems t ...

The toggleClass() function is only toggling between a single class

I'm currently facing an issue with a jQuery/Angular function that is triggered on click. <a ng-click="like()" href="#" class="like like--yes"></a> Essentially, my goal is to switch between the classes like--yes and like--no when the like ...

Toggle visibility of table using JavaScript

I am facing a small issue with hiding and showing a table. I have tried the code provided, but it seems to not be working. There are no errors in the console, so I must have missed something or made a mistake. Although I can see the data in the code, it d ...