Trigger click on specific item under nested loop Angular ngFor

一笑奈何 提交于 2019-12-11 06:24:36

问题


How to target on the specif item under the nested loop

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

Ts File

Asper my code my target is parents[5].child[0] , but its working as child 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();
}


});

Each parent has own children, Here target calculated based on all child index

How to solve this problem?


回答1:


You can set dynamic id in html element like this:

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

and then click from typescript.

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



回答2:


You can do this without ViewChild() refs.

You can add an click event listener on the child component and pass it parameters.

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

And then handle the click accordingly.

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

Here is a demo



来源:https://stackoverflow.com/questions/56289748/trigger-click-on-specific-item-under-nested-loop-angular-ngfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!