9

I have a terms page in which included links on the top. The purpose of these links is to scroll to page element that belongs to.

Is there any way to do this dynamically from the component?

Panagiotis Koursaris
  • 3,794
  • 4
  • 23
  • 46

1 Answers1

19

Eventually there is a scrollTo() method that give you the ability to scroll to any coordinates you want.

In my component I have use the method like this:

export class TermsComponent {
    @ViewChild(Content) content: Content;

    scrollTo(elementId: string) {
        let y = document.getElementById(elementId).offsetTop;
        this.content.scrollTo(0, y);
    }

}

scrollTo() get an argument with the id of the element you want to scroll to.

In my template:

<a (click)="scrollTo('section1')">Section 1</a>
<p id="section1"><b>1. The first element you want to scroll</b></p>

Ionic 4 (Muhammad Tahir):

Use this.content.scrollToPoint(0, y);

Community
  • 1
  • 1
Panagiotis Koursaris
  • 3,794
  • 4
  • 23
  • 46
  • 3
    in ionic 4. Use this.content.scrollToPoint(0, y); – Muhammad Tahir Jul 01 '19 at 05:35
  • Is it possible to use `ViewChild` instead of `getElementById`? Conflicting id's might be a nasty thing in a larger application which I would like to avoid by not using id's at all. But when I tried `ViewChild` and `element.nativeElement.offsetTop`, the scroll amount was incorrect. – andreas Oct 19 '19 at 15:31