为动态创建的 HTML 元素创建事件侦听器

Create Event Listener For Dynamically Created HTML element

在 "downMouseBtn(event)" 事件处理程序中, 我创建了元素 <div id ="rectangle"></ div>

我需要为创建的项目创建一个 eventListener。

我该如何创建它? 添加哪部分代码呢?

我需要处理动态生成项目的 mouseClick 事件。

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 */
  }
}

试试这个

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 = this.renderer.createElement('div'); /*dynamically create element*/
    // this.rectangle.setAttribute("id", "rectangle"); /*forget this by now*/

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

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

我们尽量不要直接接触 DOM,尽可能使用 render2。

这是 alligator.io 的一篇文章的 link,这是我回答的基础:
https://alligator.io/angular/using-renderer2/