我正在尝试对Angular 2项目使用scrollIntoView()。我有一个容器div,它的溢出会在数据到达组件时增大,并且需要在数据到达时滚动到div的底部。如果我使用按钮并将引用传递给它,则效果很好。
示例:
<div class="container">
<button (click)="scrollTo(target)"></button>
-----
-----
<!-- Dynamic content here -->
-----
-----
<div #target class="target" id="target"></div>
并且在组件中:
public scrollTo(el: HTMLElement) {
el.scrollIntoView({behavior: 'smooth'});
}
问题是我不想使用按钮,我需要在组件内调用scrollTo函数。我曾尝试使用@ ViewChildren,document.querySelector和document.getElementById,但没有任何效果。
示例:
1)
@ViewChildren('target') target: ElementRef;
并且在函数中:
public scrollTo() {
this.target.nativeElement.scrollIntoView({behavior: 'smooth'});
}
2)
public scrollTo() {
let element = document.getElementById('target');
element.scrollIntoView({behavior: 'smooth'});
}
3)
public scrollTo() {
let element = document.querySelector('.target');
element.scrollIntoView({behavior: 'smooth'});
}
在所有情况下,如果我通过控制台打印元素,结果都是相同的:
<div class="target" id="target" _ngcontent-ema-86=""></div>
但是仅通过按钮滚动到容器div的底部。
其他数据:该项目是PowerPoint的VSTO加载项,应在IE11上运行。感谢您的帮助。
您需要使用ViewChild
而不是ViewChildren
。当您想从模板访问单个元素时,使用ViewChild
。当模板中有多个具有相同ID(ViewChildren
)的元素时,将使用#target
。后者会给你一个数组。
尝试一下。
@ViewChild('target', { static: true }) target: ElementRef;
public scrollTo() {
this.target.nativeElement.scrollIntoView({behavior: 'smooth'});
}
查看docs以获取有关ViewChild
的更多详细信息。