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.
Use this for the router module in
app-routing.module.ts
:This will be in your HTML:
I just got this working on my own website, so I figured it would be worth posting my solution here.
And then in your component, make sure you include this:
All the other answers will work on Angular version < 6.1. But if you've got the latest version then you won't need to do these ugly hacks as Angular has fixed the issue.
here's the link to issue
All you'd need to do is set
scrollOffset
with the option of the second argument ofRouterModule.forRoot
method.Sorry for answering it bit late; There is a pre-defined function in the Angular Routing Documentation which helps us in routing with a hashtag to page anchor i.e, anchorScrolling: 'enabled'
Step-1:- First Import the RouterModule in the app.module.ts file:-
Step-2:- Go to the HTML Page, Create the navigation and add two important attributes like [routerLink] and fragment for matching the respective Div ID's:-
Step-3:- Create a section/div by matching the ID name with the fragment:-
For your reference, I have added the example below by creating a small demo which helps to solve your problem.
I've just tested very useful plugin available in nmp - ngx-scroll-to, which works great for me. However it's designed for Angular 4+, but maybe somebody will find this answer helpful.
Since the fragment property still doesn't provide anchor scrolling, this workaround did the trick for me: