0

I cannot figure out how to use the function ViewportScroller.scrollToAnchor(string anchor).

First of all - how do I define an anchor in my html? I may be confusing anchors, routerlinks and fragments.

My code which is based on fragments as of now:

export class ItemsOverviewPage implements OnInit {
    public items: Item[];

    constructor(private route: ActivatedRoute,
                private scroller: ViewportScroller) {}

    public async ngOnInit(): Promise<void> {
        const fragment = await this.route.fragment.first().toPromise();
        if (fragment !== undefined || fragment !== null) {
            this.scroller.scrollToAnchor(fragment);
        }
    }
}

The html is something like

<ion-card mode="md"
    *ngFor="let i of items"
    routerDirection="forward"
    id="{{ i.title) }}">
</ion-card>

How can I refer to the id? Or should I do an <a>...</a> around whatever I want to scroll to?

I am navigating to the page like:

this.router.navigate(['/items'], { fragment: item.title });
Liselej
  • 23
  • 1
  • 5

1 Answers1

0

I don't think you can do it that way. It seems that, when you are using a ngFor, the scrolling to the anchor gets called before the DOM is finalized. So, in your ngOnInit you can get the fragment, but won't be able to find the anchor, as the ngFor has not completed yet.

One way way to do what you want, could be to use a route parameter rather than a fragment.You can retrieve the parameter in the ngOnInit of your ItemsOverviewPageComponent and store it in a variable (e.g. _fragment), and then scroll to the anchor in the ngAfterViewInit() hook using document.getElementById(this._fragment).scrollIntoView();
Another option, could be using navigationExtras.

Even better, if you need to pass data and potentially complex objects via routes, would be to set up a service that stores the data and then inject it into the components

For more information see ActivatedRoute, NavigationExtras

Alberto L. Bonfiglio
  • 1,767
  • 23
  • 38