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

时间:2019-07-11 18:15:25

标签: angular typescript mouseevent addeventlistener

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

1 个答案:

答案 0 :(得分:0)

尝试一下

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上一篇文章的链接,这是我回答的基础:
https://alligator.io/angular/using-renderer2/