Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call scrollIntoView on an element in angular 2+

Tags:

angular

I want to call scrollIntoView on a HTML element in a component.

In angular.js 1 I can do something like this in the controller:

var element = $window.document.getElementById(id);
element.scrollIntoView({ behavior: "smooth", block: "start" });

How can I do the same thing in angular 2+ ?

like image 371
Endy Tjahjono Avatar asked Dec 03 '17 08:12

Endy Tjahjono


2 Answers

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" });
  }
}
like image 101
Endy Tjahjono Avatar answered Oct 20 '22 15:10

Endy Tjahjono


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 );
                }
            }
         }
    });
}
like image 18
Alberto L. Bonfiglio Avatar answered Oct 20 '22 16:10

Alberto L. Bonfiglio