使用angular2将click事件添加到动态创建的html元素中 [英] Adding a click event to a dynamically created html element using angular2

查看:55
本文介绍了使用angular2将click事件添加到动态创建的html元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将click事件添加到动态创建的html元素中,当前代码如下.

Im trying to add a click event to a dynamically created html element and currently the code goes as follows.

let parameterLabels = document.getElementById('parameterLabels');

    p_meter.classList.add('active', 'filtered');
    parameterLabels.innerHTML += `
        <a id="label_${parameter.name}" class="ui label transition animating scale in" 
            data-value=${parameter.name}>${parameter.name}<i id="remove_${parameter.name}" class="delete icon"></i></a>`;

    document.getElementById(`remove_${parameter.name}`).addEventListener('click', () => {
        this.removeParameter(`${parameter.name}`);
    });

当前,我通过addEventListener分配click事件,但是它仅对创建的元素有效.如果我继续创建新的动态元素,则只有最新的click事件将起作用,而先前创建的元素的click事件将不起作用.有没有办法像Angular2 (click)="removeParameter($ event)" 一样在html本身中绑定click事件,这对我也不起作用.有什么主意吗?

Currently I assign the click event via the addEventListener but it is only active for just the element which is created. If I do keep on going creating new dynamic elements, only the latest click event will work but not the click events for the previously created elements. Is there a way to bind the click event in the html itself like in angular2 (click)="removeParameter($event)" which is as well not working for me. Any idea?

推荐答案

您可以向主体添加事件侦听器,该侦听器将根据您指定的约束条件处理事件,例如:

You can add an event listener to the body which will process the event on your specified constraints like:

document.querySelector('body').addEventListener('click', (event)=> {
    if (event.target.id.toLowerCase() == `remove_${parameter.name}`) {
        this.removeParameter(`${parameter.name}`);
    }
});

注意:在Angular2中不建议直接进行DOM访问,并且它不是aot友好的代码.

Note: Direct DOM access is discouraged in Angular2 and it's not a aot-friendly code.

这篇关于使用angular2将click事件添加到动态创建的html元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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