DEV Community

loading...
Cover image for Tree Ways to Scroll to an Element using Angular

Tree Ways to Scroll to an Element using Angular

Fernando Raposo da Camara Silva
Go to https://ferfox1981.github.io/
Updated on ・2 min read

Recently I was implementing in Angular a requirement that demanded the following:

"After pressing a button, if some specific data is returned, present a warning with a link saying that the specific data exists. After clicking on that link, scroll down to the grid containing the data".

First, I tried the simplest solution, which was the use of DOM commands like Element.scrollIntoView(), or
document.getElementById("<yourTarget>").scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});

(Remeber to add id="<yourtarget" where you want to scroll)
It worked on development, and it was quite easy, but after deploying to production environment I noticed that the scroll was not working!

So, I tried another way, using Angular's ViewportScroller.
In order to do that, you have to inject ViewportScroller at Component's constructor, like constructor(private scroller: ViewportScroller) and just call this.scroller.scrollToAnchor("<yourTarget>");. Again, no big deal, and again it was NOT WORKING on production environment.

The third way to do it, is to use Router to provide navigation to the anchor I wanted. Similarly to the last option, inject Router to constructor, like constructor(private router: Router), and use the command:
this.router.navigate([], { fragment: "<yourTarget>" });
Finally it DID WORK on production environment! I don't know for sure why the previous methods failed, I read some sources that says Angular Material blocks scrolling, but I'm not sure.
In order to present the different options there's a Stackblitz as an example.
There you can click on tree buttons, each one using a different method to scroll down to some anchor.


Hope it helps someone :)

Discussion (2)

Collapse
p_leppard profile image
Paul Leppard

Helped me, thanks. I'm looking at building elearning which has sections hidden until you click the continue button, then it scrolls down to the next section. Needed a setTimeout for it to scroll to previously hidden divs but works very nicely. Thanks.

Collapse
ferfox1981 profile image
Fernando Raposo da Camara Silva Author

you're welcome!