Angular5 - Scrolling to anchor

252 Views Asked by At

I am trying to do a scroll to an anchor when I redirect to a new page. I have tried different things but without success. Now it scrolls down but it's not showing the whole HTML element I need, it shows only the header of the element. Here is the redirect to the new page

this.router.navigate(['/controllo/' + result.id], {fragment: 'assegnazioneContatto'});

And here is how I scroll to the element

ngOnInit() {
    this.routeParams.fragment.subscribe(fragment => {
        if(window.document.getElementById(fragment)) {
          this.fragment = fragment; 
          window.document.getElementById(this.fragment).scrollIntoView();
       }
      });
}

Here is the HTML element

<div class="row" [hidden]="!showAssegnazioneContatto()" id="assegnazioneContatto"></div>

What am I doing wrong? I have seen other questions here in stackoverflow but I haven't found any solution.

PS. If I run the code in the console it works fine

2

There are 2 best solutions below

2
malvadao On

From your question I have understood that the scroll is behaving in a way that it shows most of the preceding elements and the beginning of your new element.

Does this jsFiddle illustrate your situation? https://jsfiddle.net/eqzkpr8a/3/

Try playing around with the scrollIntoView()'s options: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#parameters. Specially the block property, which defines the vertical alignment of the page based on its ancestor element.

In other words, the block property may have four possible values: start, center, end, and nearest. The properties align the page vertically

  • start: at the start of its ancestor element;
  • center: at the center of its ancestor element;
  • end: at the end of its ancestor element;
  • nearest: towards the start or the end of its ancestor element, based on whatever is nearest to the scrolled element.
3
DavidG On

Two options. Have you tried .focus({ preventScroll: false }) or have you tried setting tabindex="1" of the element? Because I had to do that for my own scroll function to have it working properly.