I finally got the answer !
Ok I was on the right tracks here, to navigate from one page to anther and scroll to an element here is what you need:
We have to pages: Page1 and Page2
When we click on the photo number 4 we want to navigate to page 2 and scroll to the photo number 4.
- The Anchor <Page 2>
First thing put an Id on the elements your are listing and on which you want to be able to scroll to.
Be careful to set the elements inside a ion-content
element (required to scroll)
<ion-content>
<ion-row id="post_{{post.id}}" *ngFor="let post of posts" class="ion-padding-vertical ion-align-items-center" >
// some elements
<img src={{post.photourl}}/>
</ion-row>
</ion-content>
- The Link <Page 1>
Add the redirection link to each photo on the page1, using a function instead of routerLink seems easier for me.
HTML
<ion-col size="4" *ngFor="let post of posts" (click)="navigateTo(post.id)">
<img class="gridPhoto" [src]="doms.bypassSecurityTrustUrl(post.photourl)" />
</ion-col>
TS
navigateTo(postid) {
const navigationExtras: NavigationExtras = {
fragment: postid
};
this.navCtrl.navigateForward(['page2'], navigationExtras);
}
Sending a fragment
with the NavController is like adding to the URL #id_of_the_anchor
.
- Receive the fragment and scroll to the element
Best to put it in ionViewDidEnter
to scroll only once the page is loaded
import {ActivatedRoute, Router} from '@angular/router';
@ViewChild(IonContent, null) content: IonContent;
constructor(private route: ActivatedRoute,...) {}
ionViewDidEnter() {
this.route.fragment.subscribe( (qfragment) => {
console.log(sfragment);
const anchor = document.getElementById('post_' + qfragment);
// USE ONLY geBoundingClientRect()
this.content.scrollByPoint(0, anchor.getBoundingClientRect().top, 0);
});
}
- So we set the content variable first with
@ViewChild
, it’s require to scroll. - We use the route to get the fragment sended with the url
- We get the element by his ID
- We get his position with the function
getBoundingClientRect()
-
The trick was here, before I tried with the parameter
offsetTop
of the element but it doesn’t work anymore (don’t really known why) I could only get 0 as value. WithgetBoundingClientRect()
we got the actual distance from the element to the top.
-
The trick was here, before I tried with the parameter
- We scroll to that position with the Content element
this.content.scrollByPoint()
Hope it’s help !
Thanks