我查看了几篇相关的文章和文档,但似乎仍然无法从@ViewChild 获得预期的行为。
最终,我试图设置一个 div 的滚动位置。此元素不是组件,而是我的 HTML 中的普通 div。
为此,我尝试使用@ViewChild 来获取我需要的 DOM 元素,并设置其滚动值。 (顺便说一句,如果您知道在没有 @ViewChild(或 jQuery)的情况下完成此操作的更好方法,将不胜感激!)
目前,@ViewChild 只返回undefined。通过一些虚拟检查: - 我在 AfterViewInit 中访问我的元素 - 我在此元素上没有任何其他指令,例如 *ngIf 或 *ngFor。
这是 Controller :
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'portfolio-page',
templateUrl: './portfolio-page.component.html',
styleUrls: ['./portfolio-page.component.scss']
})
export class PortfolioPageComponent implements AfterViewInit{
@ViewChild('gallery-container') galleryContainer: ElementRef;
ngAfterViewInit(){
console.log('My element: ' + this.galleryContainer);
}
}
和模板:
<div id='gallery-container' class='gallery-image-container'>
<div class='gallery-padding'></div>
<img class='gallery-image' src='{{ coverPhotoVm }}' />
<img class='gallery-image' src='{{ imagepath }}' *ngFor='let imagepath of imagesVm' />
</div>
我的输出很简单:我的元素:未定义。
如您所见,我目前正尝试通过 ID 访问元素,但也尝试了类名。谁能提供有关 ViewChild 选择器查询所期望的内容的更多详细信息?
我也看到过使用哈希“#”作为@ViewChild 使用的选择器标识符的示例 -- -- 但这会导致我使用#gallery-container 时出现模板解析错误。
我想不出这里还有什么可能出错的地方。感谢所有帮助,谢谢!
此处提供完整代码:https://github.com/aconfee/KimbyArting/tree/master/client/KimbyArting/components/portfolio-page
最佳答案
尝试在模板中使用 ref:
<div id='gallery-container' #galleryContainer class='gallery-image-container'>
<div class='gallery-padding'></div>
<img class='gallery-image' src='{{ coverPhotoVm }}' />
<img class='gallery-image' src='{{ imagepath }}' *ngFor='let imagepath of imagesVm' />
</div>
并使用 ref 名称作为参数:
@ViewChild('galleryContainer') galleryContainer: ElementRef;
编辑
忘记提及任何这样声明的 subview 仅在 View 初始化后可用。第一次发生这种情况是在 ngAfterViewInit
中(导入并实现 AfterViewInit
接口(interface))。
ref 名称不能包含破折号,否则这将不起作用
关于dom - Angular 2 @ViewChild 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256703/