![](/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.