简体   繁体   中英

Adding a click event to a dynamically created html element using angular2

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}`);
    });

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}`);
    }
});

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

You can do something like below:

Component Side

list: Array<model> = new Array<model>();

Html Side

<div *ngFor="let item of list">
    //your html code//                               
</div>

Modifying the list will affect your html view.

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM