1

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?

1
  • 1
    I would recommend using *ngFor to create dynamic html elements by having Array<model> say list and updating the list will create dynamic html element. Commented Mar 23, 2017 at 5:23

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Ichorville no problem :-) I still want to inform you that if you can, you should create the html elements the angular way like JayakrishnanGounder described. However, I know that in some kind of situations we are forced to use this kind of code.
Im trying to implement a multiple search selection scenario where when I click on one of the search results it appears selected and the above click event is to remove the selected selection. Since the multiple results are dynamically added from a separate button click which is why i thought of using the current implementation. I will try what you and JayakrishnanGounder mentioned.
1

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

1 Comment

I will give it a try! Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.