问题
I have a simple template:
<div *ngFor="let skill of allSkills | async ">
<div class="skill-chart-with-img">
<skill-chart-view></skill-chart-view>
<div #skillImg>
some data
</div>
</div>
</div>
When I try to bind on #skillImg, I have an empty QueryList:
@ViewChildren("skillImg") private skillImgs: QueryList<ElementRef>;
ngAfterViewInit(): void {
this.skillImgs.forEach((skill: ElementRef) => {
//some work with skill
});
}
Maybe I miss something or my task have a better solution?
回答1:
The problem was in async data. The solution is to subscribe on QueryList changes
Example:
ngAfterViewInit(): void {
this.skillImgs.changes
.subscribe(() => console.log(this.skillImgs));
}
回答2:
NOTE: You have to check whether async works properly or not. Because its hard to identify any problem if associated with async pipe. But other than it, ViewChildren works with *ngFor as shown below,
export class App {
@ViewChildren("skillImg") private skillImgs: QueryList<ElementRef>;
constructor(private renderer: Renderer) {}
ngAfterViewInit(): void {
this.skillImgs.forEach((skill: ElementRef) => {
this.renderer.setElementStyle(skill.nativeElement,"background","yellow");
});
}
}
https://plnkr.co/edit/pI35tx9gXZFO1sXj9Obm?p=preview
来源:https://stackoverflow.com/questions/38951165/viewchildren-doesnt-bind-in-ngfor