1

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?

2 Answers 2

2

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();
  }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Its alternate solution, I will look this if there is no solution in angular
There is chance IDs duplicate same name, id name child1, child2, ... same repetition in each group
Index will not be duplicate, it will increment from 0 to ...n and if you have diffect groups, give group specific name in place of 'child'. Maybe something like {{'child'+ parent.name + i }}
Okay including parentIndex number also in ID name 'child01' ,'child02' etc
Yes.. that would do
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.