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