Kevin Shi
Kevin Shi

Reputation: 516

Ionic 3: programmatically scroll ion-scroll content to bottom

I have an ion-scroll component

<ion-scroll scrollY="true" style="height: 52vh;">
  {{ text }}
</ion-scroll>

The text displayed inside continues to grow (think teleprompter style), and eventually grows to be longer than the specified ion-scroll height; the container can then be manually scrolled down. The manual scrolling works fine, but is there a way to programmatically make it scroll down as more text gets added?

Upvotes: 0

Views: 4103

Answers (1)

Try in Angular 2 or higher:

page.html

  <div class="scroll" #scrollMe (change)="scrollToBottom()">
    {{ text }}
  </div>

page.ts

import { Component, ViewChild, ElementRef } from '@angular/core';
import { Content } from 'ionic-angular';

...

export class Page {

  @ViewChild('scrollMe') scrollElement: ElementRef;

  public text: String = '';

  constructor(){}

  ionViewDidLoad() {
    this.appendText();
  }

  // append text (loop...)
  appendText() {
    setTimeout( ()=> {
      this.text += 'Append more text ';
      this.appendText();
    }, 100);
  }

  // scroll to bottom (div element)
  scrollToBottom() {
    setTimeout( ()=> {
      this.scrollElement.nativeElement.scrollTop = this.scrollElement.nativeElement.scrollHeight;
    }, 50);
  }
}

page.scss

page {
    .scroll {
        max-height: 200px; // for example
        overflow-y: scroll; // show vertical scroll
    }
}

Upvotes: 2

Related Questions