在Angular 14中,ViewportScroller的使用方式略有不同。在使用ViewportScroller.scrollToPosition()之前,需要先在构造函数中声明ViewportScroller依赖注入。以下是示例代码:
import { Component, OnInit } from '@angular/core'; import { ViewportScroller } from '@angular/common';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent implements OnInit {
constructor(private viewportScroller: ViewportScroller) { }
ngOnInit() { }
scrollToTop() { this.viewportScroller.scrollToPosition([0, 0]); }
}
在上面的示例中,ViewportScroller注入到了组件的构造函数中。scrollToTop()方法会使用ViewportScroller.scrollToPosition()方法来将滚动条的位置滚动到顶部。
请注意,如果要使用scrollToPosition()方法来滚动到一个元素,可以将ViewportScroller作为依赖注入,并使用scrollToAnchor()方法来实现。