Reputation: 1823
I'm trying to fix a div when scrolling down; for that, I began with the below code, I am facing some weird issue that prevents me from detecting the scrolling behavior. On the below code console.log('bigger than 50')
does not get printed when scrolling down.
Any ideas why I can't detect the scroll event?
@Component({
templateUrl: 'outlet.html',
selector: "app-layout-nav"
})
export class place {
constructor(@Inject(DOCUMENT) private document: Document) {}
@HostListener("window:scroll", [])
onWindowScroll() {
let number = this.document.body.scrollTop;
if (number > 50) {
console.log('bigger than 50')
this.navIsFixed = true;
} else if (this.navIsFixed && number < 10) {
console.log('lower than 50')
this.navIsFixed = false;
}
}
}
Outlet.html
<div>
<div id="wrap" [class.fixed]="navIsFixed">
This should be fixed when it reaches a certain level</div>
<div>The rest of the long page should show here</div>
</div>
Upvotes: 1
Views: 3440
Reputation: 768
this might help you to detect scroll events on an element or on window https://github.com/anasAsh/ngx-scroll-event
With NPM
npm install ngx-scroll-event --save
With Yarn
yarn add ngx-scroll-event
Import ScrollEvent and add it to the imports array of your module.
// app.module.ts
import { ScrollEventModule } from 'ngx-scroll-event';
@NgModule({
imports: [
...,
ScrollEventModule,
...,
]
})
export class AppModule { }
In your template you may now add the detect-scroll
attribute and (onScroll)
event to any element.
you can also add [bottomOffest]
to change when reaching bottom is alert is true, defaults to 100, the value should be a number in pixels.
// app.awesome.component.ts
...
import { ScrollEvent } from 'ngx-scroll-event';
...
@Component({
...
template: `...
<div detect-scroll (onScroll)="handleScroll($event)" [bottomOffest]="200">
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>Bla bla bla</div>
<div>
...`,
})
export class AwesomeComponent {
public handleScroll(event: ScrollEvent) {
console.log('scroll occurred', event.originalEvent);
if (event.isReachingBottom) {
console.log(`the user is reaching the bottom`);
}
if (event.isWindowEvent) {
console.log(`This event is hapening on Window not on an element.`);
}
}
}
Upvotes: 3
Reputation: 2784
You can bind the scroll event to your container:
<div class="container" (scroll)="onScroll($event)">
<div class="scrollable_content">
</div>
</div>
Then, on your component:
onScroll(event){
const scrollTop = event.path[0].scrollTop;
}
Upvotes: 2