Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renderer2 bind event to dynamically created element using loop

Tags:

angular

ionic3

I am using Angular 4+ , import { Component, ElementRef, Renderer2 } from '@angular/core';
I have successfully generated series of element:

    const parentList = this.renderer.createElement('ul');
    let children = '';
    for(let i=0; i<totalItem; i++) {
       children += '<li id="item'+i+'">'+item.name+'</li>';
    }
    parentList .innerHTML = children;

    this.renderer.appendChild(
       this.elRef.nativeElement.querySelector('.wrapper'), 
       parentList);

Using renderer.listen, how do I bind click event to all created li throgh iteration?
My try:

for(let j=0; j<totalItem; j++) {
   let listener =
     this.renderer.listen(
        this.elRef.nativeElement.querySelector('#item'+j), 
        'click',
        (evt) => {
           this.myFunc(j);
        }
      );
}

.....

myFunc(id) {
   alert(id);
}

The problem is for each clicked li will alert the latest value of j after the iteration finished.
I want it to alert different id for each li.
I think the way I bind the event is wrong. Please help me.

like image 803
Mu Az Avatar asked Aug 05 '26 09:08

Mu Az


1 Answers

After your DOM is appended to DOM tree, you can query all DOM that starts with item id, for the same you can use querySelectorAll with [id^="item"'] expression where it says collection all elements that have attribute id's starts with item. There after loop over the collection and bind event on each element separately.

let listItems = Array.from(this.elRef.nativeElement.querySelectorAll('*[id^="item"]'))

listItems.forEach((listItem, j) => {
    this.renderer.listen(
        listItem, 
        'click',
        (evt) => {
           this.myFunc(j);
        }
    );
})
like image 159
Pankaj Parkar Avatar answered Aug 07 '26 23:08

Pankaj Parkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!