How to scroll element into view when it's clicked
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 the scrollTo(...)
method. First the view:
<ion-header>
<ion-navbar primary>
<ion-title>
<span>My App</span>
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<button ion-button text-only (click)="scrollElement()">Click me</button>
<div style="height: 600px;"></div>
<!-- Notice the #target in the p element -->
<p #target>Secret message!</p>
<div style="height: 600px;"></div>
</ion-content>
And the component code:
import { ViewChild, Component } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
@Component({
templateUrl:"home.html"
})
export class HomePage {
@ViewChild(Content) content: Content;
@ViewChild('target') target: any;
constructor() { }
public scrollElement() {
// Avoid reading the DOM directly, by using ViewChild and the target reference
this.content.scrollTo(0, this.target.nativeElement.offsetTop, 500);
}
}
The ion-content should have methods for scrolling to particular child elements, however deep. The current methods are okay, but one perspective of the purpose of ionic is to make laborious, boring code like document.getElementById
obsolete.
The methods also lack control over the scroll animation.
Hence currently the best option is the scrollIntoView
method. Attach an id to the element you wish to scroll to, then use getElementbyID to call scrollIntoView. So:
.html
...
<ion-row id="myElement">
...
</ion-row>
ts
...
scrollToMyElement() {
document.getElementById('myElement').scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
Then call the method on some DOM event or button click. If your element is conditional this will likely not work. Instead use a conditional hidden attribute or, if you must use ngIf, time the logic as such that the element is inserted first.
I've tried this with various other ionic (4) UI components and it works fine.