在Angular中,可以使用HostListener装饰器和@ViewChild装饰器来确定滚动方向。下面是一个示例代码:
HTML模板:
组件代码:
import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';
@Component({
selector: 'app-scrollable',
templateUrl: './scrollable.component.html',
styleUrls: ['./scrollable.component.css']
})
export class ScrollableComponent {
@ViewChild('scrollContainer') scrollContainerRef: ElementRef;
onScroll() {
const element: HTMLElement = this.scrollContainerRef.nativeElement;
if (element.scrollTop > 0) {
console.log('向下滚动');
} else {
console.log('向上滚动');
}
}
@HostListener('window:scroll', ['$event'])
onWindowScroll(event: Event) {
if (window.scrollY > 0) {
console.log('向下滚动');
} else {
console.log('向上滚动');
}
}
}
在上述示例中,我们使用了ViewChild装饰器来获取到包含滚动内容的div元素的引用,然后在onScroll方法中通过检查scrollTop属性来确定滚动方向。
另外,我们还使用了HostListener装饰器来监听窗口的滚动事件,并在onWindowScroll方法中通过检查window.scrollY属性来确定滚动方向。
请注意,以上代码只是一个示例,你需要根据你的具体需求进行调整和扩展。