I'm creating a webpage having full page width/height div's. While scrolling down I've two types of methods.
Scroll on Click
//HTML
<a (click)="goToDiv('about')"></a>
//JS
goToDiv(id) {
let element = document.querySelector("#"+id);
element.scrollIntoView(element);
}
Scroll on HostListener
@HostListener("window:scroll", ['$event'])
onWindowScroll($event: any): void {
this.topOffSet = window.pageYOffset;
//window.scrollTo(0, this.topOffSet+662);
}
1. How to add a scrolling animation effects?
Just like :
$('.scroll').on('click', function(e) {
$('html, body').animate({
scrollTop: $(window).height()
}, 1200);
});
2. And how to use HostListener to scroll to next div?
You can also use css property
scroll-behaviour: smooth
in combination with
var yPosition = 1000; window.scrollTo(0,yPosition)
Ref: https://developer.mozilla.org/fr/docs/Web/CSS/scroll-behavior
This one is fun. The solution, as with most things angular 2, is observables.
With a click this is easy to use. You just bind scrollTo to a click
This only works for scrolling in one direction, However this should get you started. You can make scan smarter so it subtracts if you need to go up, and instead use a function inside takeWhile that figures out the correct termination condition based on if going up or down.
The @bryan60 answer works, but I was not comfortable with it, and I preferred to use
TimerObservable
which seems less confusing for other teammates and also easier to customize for future uses.I suggest you have a shared service for times you're touching DOM, or working with scroll and other HTML element related issues; Then you can have this method on that service (otherwise having it on a component does not make any problem)
You need to pass the element to this method, here is how you can do it: