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"
});
(Remember 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.
https://stackblitz.com/edit/scrolling-types
There you can click on tree buttons, each one using a different method to scroll down to some anchor.