ShibinRagh
ShibinRagh

Reputation: 6646

Trigger click on specific item under nested loop Angular ngFor

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?

Upvotes: 1

Views: 1673

Answers (2)

Ikhlak S.
Ikhlak S.

Reputation: 9034

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

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22213

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();
  }
});

Upvotes: 2

Related Questions