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

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.


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"});
  }