要通过类在Angular中滚动到选定的元素,你可以使用ElementRef和ViewChild来获取元素的引用,并利用其scrollIntoView方法来实现滚动效果。下面是一个示例代码:
在组件类中导入ElementRef和ViewChild:
import { Component, ElementRef, ViewChild } from '@angular/core';
在组件类中定义ElementRef和ViewChild:
@Component({
selector: 'app-scroll',
template: `
`
})
export class ScrollComponent {
@ViewChild('scrollTarget', { static: false }) scrollTarget: ElementRef;
scrollToElement() {
this.scrollTarget.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
在模板中,我们使用#scrollTarget
声明了一个模板引用变量,并将其赋值给ViewChild。在按钮的click事件处理程序中,我们调用scrollIntoView方法来滚动到目标元素。
注意,我们使用了{ static: false }来确保在视图初始化之后再获取元素的引用。
希望这可以帮助到你!