How to smooth scroll to page anchor in angular 4 without plugins properly? How to smooth scroll to page anchor in angular 4 without plugins properly? angular angular

How to smooth scroll to page anchor in angular 4 without plugins properly?


I was looking for a similar solution and tried to use the ngx-scroll-to package and found that its not working in latest version of angular (angular 6+) so decided to look into other option and found a solution which uses the browser's native scrollIntoView and this seems to be the best solution so far

HTML code :

<button (click)="scrollToElement(target)"></button><div #target>Your target</div>

Ts code :

scrollToElement($element): void {    console.log($element);    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});  }


CSS only solution

html {  scroll-behavior: smooth;}

It works even after navigation or page reload.

Please note that it does not work in IE, Edge or Safari.


You can simply do this in your component.

const element = document.querySelector("#destination")if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' })

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView