How can I use the scrollTo() method for <ion-scroll>
instead of
<ion-content>
?
I'm still working on how to animate the scroll, but at least this may be considered as a solution for your scenario. Please take a look at this plunker.
Since we can't use theion-content
for scrolling, I though about getting the instance of the Scroll, then accessing the inner html scroll element, and then using the element.scrollLeft property to scroll on that element:
The element.scrollLeft property gets or sets the number of pixels that
an element's content is scrolled to the left.
So in the component code:
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
@Component({...})
export class HomePage {
@ViewChild('scroll') scroll: any;
constructor() {}
public backToStart(): void {
this.scroll.scrollElement.scrollLeft = 0;
}
public scrollToRight(): void {
this.scroll.scrollElement.scrollLeft = 500;
}
}
And in the view:
<ion-content padding>
<ion-scroll #scroll scrollX="true" style="width:100%; height:150px; white-space: nowrap;">
<div style="width:1000px;">
<div style="display:inline-block;height:100px;width:100px;border:1px solid black;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid red;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid blue;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid green;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid grey;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid brown;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid yellow;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid orange;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid pink;"></div>
<div style="display:inline-block;height:100px;width:100px;border:1px solid violet;"></div>
</div>
</ion-scroll>
<button (click)="backToStart()" ion-button text-only>Go to start</button>
<button (click)="scrollToRight()" ion-button text-only>Scroll to right!</button>
</ion-content>
By doing this.scroll.scrollElement.scrollLeft = 500;
, we can scroll the content of the ion-scroll 500px to the right. We can then go back to the start again by doing this.scroll.scrollElement.scrollLeft = 0;
.