top of page

Scroll to specific fragment in Ionic 5

Updated: Sep 8, 2022



If you want to scroll to a specific fragment in Ionic using Angular routing, first we need to learn how to send the fragment to the target component. We are going to take an example to learn, we will scroll the user to a specific case comment. For example if you have a ticket and multiple comments under it, and user clicks a notification which is related to the comment, then the user should be scrolled down to that comment.



I will demonstrate it how:


this.router.navigate(['/cases', this.CaseID], {
   queryParams: {
      title: this.Title
   }
   fragment: this.CommentID.toString()
});


Here we are going to navigate the user to the case detail page, and afterwards we will scroll the user to the specific comment after loading the case and its comments dynamically.

Using above code we will generate following url:


localhost:8100/cases/34?title=Ionic5#12

Note: I assume that you already have setup Angular routing in your application and /cases/:id is the detail page of the case in above example.


Now when you are on the Case detail page, you can fetch all details using the following code:


// Here route is an injected instance of ActivatedRoute
id = this.route.snapshot.params.id;
title = this.route.snapshot.queryParams.title;
fragment = this.route.snapshot.fragment;

You can fetch Case id, title and fragment (to where we need to scroll). According to the url, we will get following values:

id = ‘34' title = ‘Ionic5’ fragment = ‘12'

If you have separate component for comments then you can pass fragment to the comment component like this:


<case-comment [comment]="comment" *ngFor="let comment of comments" [fragment]=fragment></case-comment>

Now we will give each comment section an ID, so that we can scroll to the right comment, lets call it cc_{{commentID}:


<div id="cc_{{comment?.CommentID}}">
.... Case Comment code ....
</div>

Now you can scroll to the right comment using following code within your case-comment component.


ngAfterViewInit() {
   setTimeout(() => {
      const element = document.querySelector('#cc_' + this.fragment);
      if (element != null) {
         element.scrollIntoView({ behavior: 'smooth' });
      }
   }, 500);
}

Make sure to implement AfterViewInit within the component.

This implementation is helpful when your content is dynamic and you have separate apis for Case and case comments, therefore you have to wait for the comment component to load before you can scroll to the right section.


46 views0 comments

Comentarios


bottom of page