@ViewChild返回未定义 [英] @ViewChild returns undefined
问题描述
由于某种原因,我的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
}
-
检查是否已从'@ angular/core'正确导入ElementRef和ViewChild
Check that ElementRef and ViewChild are correctly imported from '@angular/core'
您的元素可能在AfterViewInit时根本就不存在(例如,如果有
*ngIf
.(根据您的评论似乎是这样)Your element might simply not be there at the time of AfterViewInit (in case there is a
*ngIf
, for instance. (seems the case as per your comments)在后一种情况下,您可以使用包装元素和
ViewChildren
,当添加新的子元素时会发出一些事件-有关文档的更多信息,请参见:In the latter case, you can use a wrapper element and
ViewChildren
, that emits some event when a new child element is added - more info on documentation here : https://angular.io/api/core/ViewChildrennote that there might be some issue with native
div
as per this question : @ViewChildren does not get updated with dynamically added DOM elements , but this can be worked around by using a new component that wraps your div, for instance.或者您也可以使用超时来等待组件被渲染.我必须说我发现此解决方案肮脏",但很高兴它对您有用:)
Or you can also use a timeout to wait for the component to be rendered. I must say that I find this solution 'dirty', but glad it works for you :)
这篇关于@ViewChild返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!