为动态创建的 HTML 元素创建事件侦听器 [英] Create Event Listener For Dynamically Created HTML element

查看:64
本文介绍了为动态创建的 HTML 元素创建事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Inside the "downMouseBtn(event)" Event Handler, i created element <div id ="rectangle"></ div>

我需要为创建的项目创建一个事件监听器.

I need to create an eventListener for the created item.

我怎样才能创建这个?添加代码的哪一部分?

How can I create this? What part of the code to add it?

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

I need to handle the mouseClick event for a dynamically generated item.

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.

let's try to not touch DOM directly, use render2 instead, when possible.

这里是 alligator.io 文章的链接,这是我回答的基础:
https://alligator.io/angular/using-renderer2/

here is a link to an article from alligator.io wich was the base of my answer:
https://alligator.io/angular/using-renderer2/

这篇关于为动态创建的 HTML 元素创建事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆