![](/img/trans.png)
[英]Angular ViewChildren does not see all children from ngFor immediately
[英]Angular ViewChildren from nested ngFor but group them by parent ngFor
當我嵌套 ngFor 時,如何按父 ngFor 對子項進行分組?
所以我有這樣的事情:
html:
<div *ngFor="let item of firstChildrenGroupData">
<app-child #firstChildrenGroup [data]="item.data"></app-child>
</div>
<button (click)="doSomethingForGroup(firstGroup)">Click here</button>
<div *ngFor="let item of secondChildrenGroupData">
<app-child #secondChildrenGroup [data]="item.data"></app-child>
</div>
<button (click)="doSomethingForGroup(secondGroup)">Click here</button>
ts:
@ViewChildren('firstChildrenGroup') firstGroup: QueryList<ChildComponent>;
@ViewChildren('secondChildrenGroup') secondGroup: QueryList<ChildComponent>;
doSomethingForGroup(group: QueryList<ChildComponent>) {
group.foreach(item => {
item.doAction();
})
}
我想實現這個
html:
<div *ngFor="let group of ChildrenGroups">
<div #group>
<div *ngFor="let item of group.childrenData">
<app-child #child [data]="item.data"></app-child>
</div>
<button (click)="doSomethingForGroup(????)">Click here</button>
</div>
</div>
這是錯誤的,因為如果我在按鈕中使用它,現在將對所有孩子采取行動,但我只想對每個按鈕的一組孩子采取行動。
@ViewChildren('child') allChildren: QueryList<ChildComponent>
@edit:也許我可以做一些類似於另一個組件<app-parent></app-parent>
的事情,它將獲取組數據,然后在這個 ngFor 和<app-child></appChild>
內部,但我想避免制作另一個中間的組件僅用於分組。
你可以在做某事之前“過濾”查詢列表,如果我認為你的 item.data 是一個屬性“groupId”
<button (click)="doSomethingForGroup(group.groupId)">Click here</button>
doSomethingForGroup(groupId)
{
this.secondGroup.filter((item:any)=>item.data.groupId==groupId)
.forEach(item=>{
...do domething...
})
}
如果沒有屬性 groupId,則可以作為參數 group.childrenData 傳遞
<button (click)="doSomethingForGroup(group.childrenData)">Click here</button>
並使用一些像
doSomethingForGroup(childrenData)
{
this.secondGroup.filter((item:any)=>childrenData.find(d=>d==x.item.data))
.forEach(item=>{
...do domething...
})
}
注意:我不檢查代碼,僅用作靈感
我會考慮制作
<div *ngFor="let item of group.childrenData">
<app-child #child [data]="item.data"></app-child>
</div>
<button (click)="doSomethingForGroup(????)">Click here</button>```
它自己的組件和傳入的組,並讓父級迭代這個組件。 您可以完全避免使用 ViewChildren,因為這個新組件中的按鈕可以使用傳遞給它的組數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.