Listen for Events on HTML Elements Created Dynamically

While working inside the "downMouseBtn(event)" Event Handler, I decided to create a new element with the code

<div id ="rectangle"></ div>

Now, my next step is to establish an eventListener for this newly created item.

Could someone guide me on how to achieve this? Which part of the existing code should I modify and what specific lines need to be added?

The main goal here is to handle the mouseClick event for an item that has been generated dynamically.

import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';

@Component({ selector: 'app-editor', templateUrl:'./editor.component.html', styleUrls: ['./editor.component.css']})

export class EditorComponent implements OnInit {
  constructor(private renderer: Renderer2, private elRef: ElementRef) { }

  ngOnInit() { }

  downMouseBtn(event) {
    this.rectangle = document.createElement('div'); /*dynamically create element*/
    this.rectangle.setAttribute("id", "rectangle"); /*set id for element*/

    this.renderer.appendChild(this.editorPhotoWrapper.nativeElement, this.rectangle); /*add element via renderer*/

    /* problemAreaStart */
    this.renderer.listen(this.rectangle.nativeElement, 'click', (event) => {
      console.log("test");
    });    
    /* problemAreaStop */
  }
}

Answer №1

Give this a shot!

import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';

@Component({ selector: 'app-editor', templateUrl:'./editor.component.html', styleUrls: ['./editor.component.css']})

export class EditorComponent implements OnInit {
  constructor(private renderer: Renderer2, private elRef: ElementRef) { }

  ngOnInit() { }

  mouseButtonDown(event) {
    this.rectangle = this.renderer.createElement('div'); /*dynamically create element*/
    // this.rectangle.setAttribute("id", "rectangle"); /*for now, let's skip this */

    this.renderer.appendChild(this.editorPhotoWrapper.nativeElement, this.rectangle); /*add element using renderer*/

    /* issue areaStart */
    this.renderer.listen(this.rectangle, 'click', (event) => {
      console.log("test");
    });    
    /* problemAreaStop */
  }
}

Let's aim to avoid direct DOM manipulation and use render2 whenever feasible.

Check out this article on alligator.io which served as the foundation for my response:
https://alligator.io/angular/using-renderer2/

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

Troubleshooting error handling in Angular HttpClient proves to be quite

The Angular documentation regarding the new HttpClient can be found at https://angular.io/guide/http. Within this documentation, there is a section titled "Getting error details" which provides an example similar to the one displayed below. I have made mod ...

Having trouble getting navigation to work using react-navigation and typescript in a react-native project?

Currently, I am exploring the use of TypeScript in my React Native project for the first time. While I have a basic understanding of TypeScript, I am encountering some issues with third-party libraries like react-navigation. My project consists of parent ( ...

Issue with Angular 2 Teamcity Error

Hey team, I'm encountering an error in TeamCity and could use some assistance. [05:40:13][Step 1/6] Update assembly versions: Scanning checkout directory for assembly information related files to update version to 12 [05:40:13][Step 1/6] scan: Search ...

Using SCSS variables in TypeScript inside a Vue project

Has anyone had experience with importing SASS (scss) variables into JavaScript in a TypeScript Vue 3 project? // @/assets/styles/colors.scss $white: #fff; // @/assets/styles/_exports.scss @import "./colors.scss"; :export { white: $white; } <templat ...

What is the best way to configure distinct proxy and backend API URLs for development and production environments?

My goal is to seamlessly link an Angular / C# Web Api project on localhost while developing. For this, I typically use the following URL in the Angular app: http://localhost:5000/api/something However, this setup does not work once deployed. Ideally, I w ...

The TypeScript error occurs when trying to set the state of a component: The argument 'X' cannot be assigned to the parameter of type '() => void'

When I attempt to call setState, I encounter a TypeScript error. Here is the code snippet causing the issue: updateRequests(requests: any, cb:Function|null = null) { this.setState( { requests: { ...this.state.requests, ...

Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed? When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to ...

Enhance your Three.js development with TypeScript autocomplete

In my project using Node.js, Typescript, and Three.js, I have set up the commonjs syntax for module imports in my tsconfig.json file like this: { "compilerOptions": { "module": "commonjs" } } I installed Three.js via NPM and created a typescript ...

unable to locate the custom npm package within my service

There is a similar inquiry posted here: My custom NPM Package is not found, but unfortunately, the solution provided did not fix my issue. I am encountering an error stating: "Could not find a declaration file for module '@dc_microurb/common' ...

Is it possible to create CSS code in an external file instead of using a style element in Angular2?

Is there a reason why angular2 generates the style code in the head style element instead of an external file? I was hoping to bundle the style code in a bundle.css file and then link it in the HTML head. ...

Is there an issue with the proper execution of keypresses/updates in the code

I'm currently stuck while trying to develop a game in Javascript. My challenge lies in detecting keypresses and constantly checking if they are being held down to move the character. Below is the code I have been using: var THREE; var keys; var updat ...

Ways to implement the flow of change occurrences in the mat-select component

Seeking assistance with utilizing the optionSelectionChanges observable property within Angular Material's mat-select component. This property provides a combined stream of all child options' change events. I'm looking to retrieve the previ ...

List of Ionic Cordova plugins sorted by Android version

Seeking guidance on how to determine which versions of Cordova plugins are compatible with Android 5.0.0. When attempting to build with the latest plugins, I encounter errors indicating that they are not supported in this version of Android. For instance: ...

What is the method for opening the image gallery in a Progressive Web App (PWA)?

I am struggling to figure out how to access the image gallery from a Progressive Web App (PWA). The PWA allows me to take pictures and upload them on a desktop, but when it comes to a mobile device, I can only access the camera to take photos. I have tried ...

Angular 6's Select feature is failing to properly update user information

We are currently facing an issue with our user profile edit form. When users try to update their information by changing simple input fields, the changes are reflected successfully. However, when they make selections in dropdown menus, the values do not ge ...

Sending input in a nested event listener

I am currently utilizing Highcharts for the purpose of showcasing an interactive map with custom countries. I have a specific requirement to enable the drilldown functionality, which involves clicking on a country to zoom in on another map displaying inter ...

Utilizing Typescript to filter a table and generate a transformed output for each item

What's the best way to return each mapped element of an array using an optimized approach like this: this.itemsList= res.map( ( x, index ) => { x.id = x.code; x.itemName = x.name; return x; }); I've tried optimizing it with a second me ...

Steps for enabling a function to return an undefined type

After extensive review, I have discovered that TypeScript has numerous hidden nuances, which make it less strict and accurate. I prefer to utilize 'undefined' as the return type for functions because it accurately reflects the reality of the sit ...

What exactly is the most efficient method for validating fields within an Angular template?

My reactive form is currently displaying a validation message for each field that is not valid. However, I noticed that I was repeatedly using the check !!(!form.get(field)?.valid && form.get(field)?.touched); in every input field. So, I decided to ...

What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3). As an example, TSC has no problem transpiling for(var int of intArray); ...