angular – @ViewChild返回undefined

前端之家收集整理的这篇文章主要介绍了angular – @ViewChild返回undefined前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
出于某种原因,我的Angular 5 App中的@ViewChild不起作用.
我在我的组件中定义了这样的:

案例detail.component.html:

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

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

案例detail.component.ts

@ViewChild('innerTabContent') tabContentElement: ElementRef;

我想在组件中访问它:
案例detail.component.ts

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

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

任何帮助是极大的赞赏 :)

解决方法

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

这个plunker演示:https://plnkr.co/edit/KzWnkE5Hvp7NUow6YAxy

零件 :

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

>检查是否从’@ angular / core’正确导入了ElementRef和ViewChild
>你的元素可能在AfterViewInit时根本就不存在(例如,如果有一个* ngIf.(根据你的评论似乎是这种情况)

在后一种情况下,您可以使用包装元素和ViewChildren,它会在添加新的子元素时发出一些事件 – 有关文档的更多信息:https://angular.io/api/core/ViewChildren

请注意,根据这个问题,本机div可能存在一些问题:@ViewChildren does not get updated with dynamically added DOM elements,但这可以通过使用包装div的新组件来解决.

编辑

或者您也可以使用超时等待呈现组件.我必须说我觉得这个解决方案“很脏”,但很高兴它适合你:)

猜你在找的Angularjs相关文章