【问题标题】:ElementRef not contained within source codeElementRef 不包含在源代码中
【发布时间】:2023-04-02 04:18:02
【问题描述】:

在我的模板中,我使用 *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&lt;ElementRef&gt;;

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

  	

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

【问题讨论】:

  • 这段代码在应用程序的什么地方?在 ngAfterViewInit 生命周期挂钩之后,您才能访问 ViewChildren 元素。

标签: angular angular6 angular-animations


【解决方案1】:

虽然我无法确定您在哪里运行日志记录代码,但我确信这是因为直到 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);

【讨论】:

  • 谢谢。没错,当我使用 ngOnInit 时,使用了对元素的不正确引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多