I wish to add some links on my Angular2 page, that when click, will jump to specific positions within that page, like what normal hashtags do. So the links would be something like
/users/123#userInfo
/users/123#userPhoto
/users/123#userLikes
etc.
I don't think I need HashLocationStrategy, as I'm fine with the normal Angular2 way, but if I add directly, the link would actually jump to the root, not somewhere on the same page. Any direction is appreciated, thanks.
Unlike other answers I'd additionally also add
focus()
along withscrollIntoView()
. Also I'm usingsetTimeout
since it jumps to top otherwise when changing the URL. Not sure what was the reason for that but it seemssetTimeout
does the workaround.Origin:
Destination:
Typescript:
Solutions above didn't work for me... This one did it:
First, prepare
MyAppComponent
for automatic scrolling in ngAfterViewChecked()...Then, navigate to
my-app-route
sendingprodID
hashtagI had the same issue. The solution : using View port Scroller https://angular.io/api/common/ViewportScroller#scrolltoanchor
-- Component's code :
A simple solution that works for pages without any query parameters, is browser back / forward, router and deep-linking compliant.
The timeout is simply to allow the page to load any dynamic data "protected" by an *ngIf. This can also be used to scroll to the top of the page when changing route - just provide a default top anchor tag.
Here is another workaround with refernce to JavierFuentes answer:
in script:
This allows user to directly scroll to element, if user directly lands on the page having hashtag in url.
But in this case, I have subscribed route Fragment in
ngAfterViewChecked
butngAfterViewChecked()
gets called continuously per everyngDoCheck
and it doesn't allows user to scroll back to top, sorouteFragmentSubscription.unsubscribe
is called after a timeout of 0 millis after view is scrolled to element.Additionally
gotoHashtag
method is defined to scroll to element when user specifically clicks on the anchor tag.Update:
If url has querystrings,
[routerLink]="['self-route', id]"
in anchor wont preserve the querystrings. I tried following workaround for the same:After reading all of the solutions, I looked for a component and I found one which does exactly what the original question asked for: scrolling to anchor links. https://www.npmjs.com/package/ng2-scroll-to
When you install it, you use syntax like:
It has worked really well for me.