触发点击嵌套循环Angular ngFor下的特定项目
Trigger click on specific item under nested loop Angular ngFor
如何定位到嵌套循环下的特定项目
<ul #parents *ngFor="let parent of parents">
<li #child *ngFor="let child of parents.childGroup"> {{child.name}} </li>
<ul>
Ts 文件
根据我的代码,我的目标是 parents[5].child[0]
,但它的工作方式是 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();
}
});
每个parent都有自己的children,这里的target是根据所有child指数计算的
如何解决这个问题?
您可以在 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();
}
});
你可以在没有 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
如何定位到嵌套循环下的特定项目
<ul #parents *ngFor="let parent of parents">
<li #child *ngFor="let child of parents.childGroup"> {{child.name}} </li>
<ul>
Ts 文件
根据我的代码,我的目标是 parents[5].child[0]
,但它的工作方式是 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();
}
});
每个parent都有自己的children,这里的target是根据所有child指数计算的
如何解决这个问题?
您可以在 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();
}
});
你可以在没有 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