Am looking for something similar to scrollIntoView()
within Ionic2 to use when I click on a button, for example.
None of the methods detailed in ion-content
help.
Am looking for something similar to scrollIntoView()
within Ionic2 to use when I click on a button, for example.
None of the methods detailed in ion-content
help.
Please take a look at this working plunker
You can use the
scrollTo(x,y,duration)
method (docs). The code is pretty simple, first we obtain the position of the target element (a<p></p>
in this case) and then we use that in thescrollTo(...)
method. First the view:And the component code:
I noticed the above solution don't work well with Angular Universal server-side rendering (SSR) due to
document
not being available server-side.Hence I wrote a convenient plugin to achieve scrolling to elements in Angular 4+ that work with
AoT
andSSR
NPM
ngx-scroll-to
GitHub
ngx-scroll-to
I'd use an anker link in HTML.
Just give the elemnt and id="scrollXYZ" and wrap the button in an
Example:
I was trying to do this in Ionic 3 and due to the fact that
<Element>.offsetTop
was returning10
(the padding on the top of the element) instead of the distance to the top of the page (much larger unknown number) I ending up just using<Element>.scrollIntoView()
, which worked well for me.To get the
<Element>
object I useddocument.getElementById()
, but there are many other options on how to get a handle on that.