ElementRef 不包含在源代码中

ElementRef not contained within source code

在我的模板中,我使用 *ngFor

<div #listofbars *ngFor="let points of pointsNormalized; let i =index" [attr.data-index]="i">

<div *ngIf="i < 10" class="ranking d-flex align-items-center" [ngClass]="setBarClass(i)" [attr.id]="'bar-id-' + i">
   

然后我尝试像这样访问第 0 个子元素:

@ViewChildren("listofbars")  list_container: QueryList<ElementRef>;

if (this.list_container) {
 if (this.list_container.toArray()[0]) {
  console.log(this.list_container.toArray()[0].nativeElement);
 }
}

   

但是,当我检查 Chrome 控制台时,该元素实际上并不包含在 html 源中。我正在尝试使用元素引用来构建动画,但是当我访问 ngFor 中的元素时它不起作用(当我在 ngFor 之外的元素上尝试它时它起作用了)。在 ngFor 指令中获取本机元素引用的正确方法是什么?

虽然我无法确定您 运行 日志记录代码在哪里,但我敢肯定这是因为直到 ngAfterContentInit 才设置 ViewChildren。因此,需要做的第一件事就是将您的代码放入 ngAfterViewInit() { }(在contentInit之后触发)。
接下来,我将订阅 QueryList 上的更改。所以:

@ViewChildren("listofbars")  childrenQuery: QueryList<ElementRef>;

ngAfterViewInit() {
    this.childrenQuery
      .changes
      .subscribe((list) => {
        console.log("Native element", list.toArray()[0].nativeElement);
      })
}

或者如果你真的只需要第一个条目,为了美观你可以使用

console.log("Native element", list.first.nativeElement);