簡體   English   中英

觸發單擊嵌套循環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] ,但它作為孩子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();
}


});

每個父母都有自己的孩子,此處的目標是根據所有孩子指數計算得出的

如何解決這個問題呢?

您可以在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()引用的情況下執行此ViewChild()

您可以在子組件上添加click事件監聽器,並傳遞其參數。

<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}`)
  }
}

這是一個演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM