@ViewChild返回未定义 [英] @ViewChild returns undefined

查看:94
本文介绍了@ViewChild返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我的Angular 5应用程序中的@ViewChild无法正常工作. 我已经在我的组件中定义了这样的内容:

For some reason my @ViewChild in my Angular 5 App does not work. I have defined it like this in my component:

case-detail.component.html:

<div class="inner-tab-content" #innerTabContent>
    <!-- // more content here -->
</div>

我已经在控制器中(在构造函数之上)实现了@ViewChild,如下所示:

I have implemented @ViewChild in my controller (above the constructor) like this:

case-detail.component.ts

@ViewChild('innerTabContent') tabContentElement: ElementRef;

我想在组件中访问它: case-detail.component.ts

And I want to access it here in the component: case-detail.component.ts

ngAfterViewInit() {
    console.log("scroll top: " + this.tabContentElement.nativeElement);
}

我已经实现了AfterViewInit接口. ngAfterViewInit()被正确调用.但是,this.tabContentElement始终为undefined.

I've implemented the AfterViewInit interface. ngAfterViewInit() is called correctly. However, this.tabContentElement is always undefined.

非常感谢您的帮助:)

推荐答案

ViewChild()在您所描述的最新plunker Angular版本上可以正常工作.

ViewChild() works fine on latest plunker Angular version with the scenario you describe.

此监听器中的演示: https://plnkr.co/edit/KzWnkE5Hvp7NUow6YAxy

组件:

ngAfterViewInit() {
    console.log(this.testView); // correctly outputs the element in console, not undefined
}

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆