[英]Window scroll event using @HostListener not working
I have problem making sticky header when scrolling down, in an Angular 4 application.在 Angular 4 应用程序中,向下滚动时制作粘性标题时遇到问题。 Scroll event can't be detected.
无法检测到滚动事件。
Header is placed in the layout component, and the content I want to be scrolling is placed in routes component. Header放在layout组件中,我要滚动的内容放在routes组件中。 May that be the problem?
这可能是问题吗?
This is the code I implemented.这是我实现的代码。
In layout.component.ts在 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;
}
}
}
In layout.component.html在 layout.component.html
<div [class.fixed]="navIsFixed" class="header">
I just had the same problem, all what I had to do was to make sure that the component element is actually what is scrolling & that it has a overflow
property with values scroll
or auto
.我只是遇到了同样的问题,我所要做的就是确保组件元素实际上是滚动的并且它具有值为
scroll
或auto
的overflow
属性。
Otherwise just this worked:否则就是这样:
@HostListener('scroll')
public asd(): void {
console.log('scrolling');
}
Your layout must be the source of the issue.您的布局必须是问题的根源。 The scroll event works only when the the component template element can actually scroll.
只有当组件模板元素可以真正滚动时,滚动事件才起作用。
Make sure the div has overflow property set to scroll.确保 div 的溢出属性设置为滚动。 Also, change the div dimensions so the scroll could trigger.
此外,更改 div 尺寸以便可以触发滚动。
In order to make it work, I would suggest to make it to the directive and set to a div that has 100vh in height and 100vw in width.为了使其工作,我建议将其设置为指令并设置为高度为 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');
}
}
See this stackblitz that I made.看看我做的这个stackblitz 。
This should give you scroll events:这应该给你滚动事件:
@HostListener('scroll', ['$event'])
onScroll(event) {
...
}
or或
<div (scroll)="onScroll($event)"
I have the same issue, I added this to "nav.component":我有同样的问题,我将它添加到“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.