简体   繁体   English

Renderer2 使用循环将事件绑定到动态创建的元素

[英]Renderer2 bind event to dynamically created element using loop

I am using Angular 4+ , import { Component, ElementRef, Renderer2 } from '@angular/core';我正在使用 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?使用renderer.listen ,如何将 click 事件绑定到所有创建的li throgh 迭代?
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.问题是每次点击li都会在迭代完成后提醒j的最新值。
I want it to alert different id for each li .我希望它为每个li提醒不同的id
I think the way I bind the event is wrong.我认为我绑定事件的方式是错误的。 Please help me.请帮我。

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 .在您的 DOM 附加到 DOM 树后,您可以查询所有以item id 开头的 DOM,同样您可以使用querySelectorAll[id^="item"']表达式,它表示集合所有具有属性id的元素以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);
        }
    );
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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