【发布时间】:2023-03-21 11:35:01
【问题描述】:
由于某种原因,我的 Angular 5 应用程序中的 @ViewChild 不起作用。 我在我的组件中这样定义它:
case-detail.component.html:
<div class="inner-tab-content" #innerTabContent>
<!-- // more content here -->
</div>
我已经在我的控制器中(在构造函数上方)实现了@ViewChild,如下所示:
case-detail.component.ts
@ViewChild('innerTabContent') tabContentElement: ElementRef;
我想在组件中访问它: case-detail.component.ts
ngAfterViewInit() {
console.log("scroll top: " + this.tabContentElement.nativeElement);
}
我已经实现了AfterViewInit 接口。 ngAfterViewInit() 被正确调用。但是,this.tabContentElement 始终是 undefined。
非常感谢任何帮助:)
【问题讨论】:
-
你能告诉我们你是如何实现@ViewChild的吗?
-
当然,刚刚更新了我的答案:)
-
如果您使用
#innerTabContent,您将直接拥有elementRef 而不是nativeElement。console.log(this.tabContentElement)你会得到 HTML 元素 -
@Aravind 那也不起作用。 this.tabContentElement 不幸的是未定义。
-
@dave0688 定义 #innerTabContent 元素的块是否可能在某些
*ngIf或其他在 afterviewinit 时未呈现的条件模板中?