How to call scrollIntoView on an element in angular 2+

First add a template reference variable in the element (the #myElem):

<p #myElem>Scroll to here!</p>

Then create a property in the component with attribute ViewChild, and call .nativeElement.scrollIntoView on it:

export class MyComponent {
  @ViewChild("myElem") MyProp: ElementRef;

  ngOnInit() {
    this.MyProp.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
  }
}

You could intercept the NavigationEnd event

    private scrollToSectionHook() {
    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            const tree = this.router.parseUrl(this.router.url);
            if (tree.fragment) {
                const element = document.querySelector('#' + tree.fragment);
                if (element) {
                    setTimeout(() => {
                        element.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
                    }, 500 );
                }
            }
         }
    });
}

You can achieve the same animated scroll to the element in Angular 2+, simply pass the element on click, like so:

<button mat-fab (click)="scroll(target)">
    <i class="material-icons">
      arrow_drop_down
    </i>
 </button>
<div #target></div>

public scroll(element: any) {
    element.scrollIntoView({ behavior: 'smooth' });
  }

Tags:

Angular