【问题标题】:Trigger click on specific item under nested loop Angular ngFor触发单击嵌套循环Angular ngFor下的特定项目
【发布时间】:2019-10-10 21:15:23
【问题描述】:

如何定位嵌套循环下的特定项

<ul #parents *ngFor="let parent of parents">
     <li #child *ngFor="let child of parents.childGroup"> {{child.name}} </li>
<ul>

Ts 文件

按照我的代码,我的目标是 parents[5].child[0] ,但它作为孩子工作 parents[0].child[0]

@ViewChildren('parents') parents : QueryList<ElementRef>
 @ViewChildren('child') child: QueryList<ElementRef>

this.parents.forEach((item, index) => {
if (index === 5 ) {
(this.child.find( (item , index) => index === 0 ).nativeElement as HTMLElement).click();
}


});

每个父母都有自己的孩子,这里的目标是根据所有孩子索引计算的

如何解决这个问题?

【问题讨论】:

    标签: angular angular6 angular7 ngfor


    【解决方案1】:

    您可以像这样在html元素中设置动态id

    <ul #parents *ngFor="let parent of parents">
         <li #child *ngFor="let child of parents.childGroup;let i=index" id="{{'child'+ i }}">
              {{child.name}} 
        </li>
    <ul>
    

    然后从打字稿中点击。

    this.parents.forEach((item, index) => {
      if (index === 5 ) {
        document.getElementById("child" + index  ).click();
      }
    });
    

    【讨论】:

    • 它的替代解决方案,如果角度没有解决方案,我会看这个
    • 有机会 ID 重复相同的名称,id 名称 child1,child2,...在每个组中相同的重复
    • 索引不会重复,它会从 0 增加到 ...n,如果您有不同的组,请给出组特定的名称来代替“孩子”。也许像{{'child'+ parent.name + i }}
    • 好的,在 ID 名称 'child01' 、'child02' 等中也包含 parentIndex 编号
    • 是的.. 可以的
    【解决方案2】:

    您可以在没有ViewChild() 参考的情况下执行此操作。

    您可以在子组件上添加点击事件监听器并传递参数。

    <li *ngFor="let child of parent.children" (click)="handleClick(parent, child)">
    

    然后相应地处理点击。

    handleClick(parent, child){
      console.log(parent);
      if(this.parents[1] === parent && (parent.children.indexOf(child)) === 1 ){
        alert(`You clicked ${child} of parent ${parent.id}`)
      }
    }
    

    这是demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-22
      • 2017-09-30
      • 2020-01-23
      • 2017-03-30
      • 2021-01-12
      • 2018-06-08
      • 1970-01-01
      相关资源
      最近更新 更多