加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – @ViewChild返回undefined

发布时间:2020-12-17 06:52:10 所属栏目:安全 来源:网络整理
导读:出于某种原因,我的Angular 5 App中的@ViewChild不起作用. 我在我的组件中定义了这样的: 案例detail.component.html: div class="inner-tab-content" #innerTabContent !-- // more content here --/div 我已经在我的控制器中实现了@ViewChild(在构造函数之
出于某种原因,我的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的新组件来解决.

编辑

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读