[英]Angular 8 @HostListener('window:scroll', []) not working
[英]Window scroll event using @HostListener not working
在 Angular 4 應用程序中,向下滾動時制作粘性標題時遇到問題。 無法檢測到滾動事件。
Header放在layout組件中,我要滾動的內容放在routes組件中。 這可能是問題嗎?
這是我實現的代碼。
在 layout.component.ts 中
import { Component, OnInit, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";
@Component({
selector: 'app-layout',
templateUrl: './layout.component.html',
styleUrls: ['./layout.component.css']
})
export class LayoutComponent implements OnInit {
public navIsFixed: boolean = false;
constructor(public router: Router, @Inject(DOCUMENT) private document: any) { }
@HostListener('window:scroll', [ ])
onWindowScroll(){
const number = window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop || 0;
if (number > 50) {
this.navIsFixed = true;
} else if (this.navIsFixed && number < 10) {
this.navIsFixed = false;
}
}
}
在 layout.component.html
<div [class.fixed]="navIsFixed" class="header">
我只是遇到了同樣的問題,我所要做的就是確保組件元素實際上是滾動的並且它具有值為scroll
或auto
的overflow
屬性。
否則就是這樣:
@HostListener('scroll')
public asd(): void {
console.log('scrolling');
}
您的布局必須是問題的根源。 只有當組件模板元素可以真正滾動時,滾動事件才起作用。
確保 div 的溢出屬性設置為滾動。 此外,更改 div 尺寸以便可以觸發滾動。
為了使其工作,我建議將其設置為指令並設置為高度為 100vh 和寬度為 100vw 的 div。
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({ selector: '[trackScroll]' })
export class TrackScrollDirective {
constructor(private el: ElementRef) {
}
@HostListener('document:scroll', [])
onScroll(): void {
console.log('I am scrolled');
}
}
看看我做的這個stackblitz 。
這應該給你滾動事件:
@HostListener('scroll', ['$event'])
onScroll(event) {
...
}
或
<div (scroll)="onScroll($event)"
我有同樣的問題,我將它添加到“nav.component”中:
@HostListener('window:scroll', [])
onWindowScroll() {
console.log(window.scrollY);
if (window.scrollY > 90) {
this.isSticky = true;
} else {
this.isSticky = false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.