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.