Ichorville
Ichorville

Reputation: 944

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?

Upvotes: 1

Views: 3680

Answers (2)

Jayakrishnan
Jayakrishnan

Reputation: 4294

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!!

Upvotes: 1

eko
eko

Reputation: 40647

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.

Upvotes: 3

Related Questions