0

Does anybody know the proper implementation of scrolling to anchor. This approach doesn't work: Angular2 scroll to element that has *ngIf

Here is the template that has references to other components:

<app-app1 id="id1"></app-app1>
<app-app2 id="id2"></app-app2>
<app-app3 id="id3" *ngIf="test"></app-app3>

By clicking on a button I'd like to scroll to the appropriate section:

let elm = document.querySelector("#id1");
if (elm)
  elm.scrollIntoView();

The scrollIntoView() is executed but it scroll to wrong place (like to the middle of the section) and doesn't work for app-app3 at all.

Kim Kern
  • 43,715
  • 16
  • 163
  • 170
John Glabb
  • 1,014
  • 4
  • 15
  • 38

1 Answers1

0

I fixed it this way: 1. Remove "id3" from app selector component:

   change: <app-app3 id="id3" *ngIf="test"></app-app3>
   to:     <app-app3 *ngIf="test"></app-app3>
  1. Put new div inside component at the very top:

< div id="id3"> < /div >

  1. Change:
let elm = document.querySelector("#id3");
if (elm)
  elm.scrollIntoView();

to:

let elm = document.getElementById("id3");
elm.scrollIntoView({behavior: "instant", block: "center", inline: "center"});
John Glabb
  • 1,014
  • 4
  • 15
  • 38