ViewChildren在ngFor中没有绑定

时间:2016-08-15 07:44:02

标签: angular angular2-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>

当我尝试绑定#skillImg时,我有一个空的QueryList:

@ViewChildren("skillImg") private skillImgs: QueryList<ElementRef>;
ngAfterViewInit(): void {
        this.skillImgs.forEach((skill: ElementRef) => {
           //some work with skill
        });
}

也许我错过了什么或者我的任务有更好的解决方案?

3 个答案:

答案 0 :(得分:7)

问题在于异步数据。解决方案是订阅QueryList更改

示例:

ngAfterViewInit(): void {
    this.skillImgs.changes
        .subscribe(() => console.log(this.skillImgs));
}

答案 1 :(得分:1)

注意:您必须检查异步是否正常工作。因为如果与异步管道相关联,很难识别任何问题。但除此之外,ViewChildren使用* ngFor,如下所示,

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

答案 2 :(得分:1)

此问题仅发生在开发模式下。您可以通过多种方式处理此问题。

  1. 显式变化检测
constructor(private changeDetector: ChangeDetectorRef) {
}

ngAfterViewInit() {
  this.skillImgs.changes.subscribe(() => {
    //make changes here
    this.changeDetector.detectChanges();
  })
}

  1. 使用承诺
    ngAfterViewInit() {
        this.skillImgs.changes.subscribe(()=>{
            Promise.resolve().then(()=>{
               //make changes here
            });
         })
     }
  1. 超时
    ngAfterViewInit() {
    this.skillImgs.changes.subscribe(()=>{
      settimeout(()=>{
        //make changes here
      });
    }, 0)’
  }

引用自 here