ViewChildren doesn't bind in ngFor

早过忘川 提交于 2021-02-07 13:15:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!