在Angular 7中,你可以使用@ViewChild
装饰器来获取到虚拟滚动的容器元素,并使用scrollToOffset()
方法来设置滚动位置。以下是一个示例代码:
在HTML模板中,你需要给虚拟滚动容器元素添加一个引用名字:
在组件的代码中,你可以使用@ViewChild
来获取到该元素,并在需要的地方调用scrollToOffset()
方法来设置滚动位置:
import { Component, ViewChild } from '@angular/core';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
@Component({
selector: 'app-example',
template: `
`,
})
export class ExampleComponent {
@ViewChild('scrollViewport', { static: true }) scrollViewport: CdkVirtualScrollViewport;
scrollToEnd() {
// 获取最大滚动位置
const maxScrollOffset = this.scrollViewport.measureScrollOffset('bottom');
// 设置滚动位置为最大值
this.scrollViewport.scrollToOffset(maxScrollOffset);
}
}
在上面的示例中,我们使用@ViewChild
来获取到#scrollViewport
元素的引用,并将其赋值给scrollViewport
变量。然后,我们可以在scrollToEnd()
方法中使用measureScrollOffset()
来获取到最大滚动位置,并使用scrollToOffset()
方法来设置滚动位置为最大值。