So I used the following post to figure out how to add a fragment to the url.
Angular2 Routing with Hashtag to page anchor
And the fragment gets added fine, however the page doesn't move to the resulting anchor. I have tried using both the name
and id
attribute on the destination div
, but neither seem to work.
I'm using Angular Version 2.0.0-rc.3, and router version 3.0.0-alpha.6.
Thanks!
<a [routerLink]="[]" fragment="destination">Go TO DIV</a>
<div id='destination'>
<h2>Destination</h2>
</div>
There is enough space between the 2 elements to tell if the page actually moves.
And as said before, the url correctly adds #destination
to itself.
A workaround might be to write a function in your component that sets the location.hash to the id of the div you want to navigate to.
<a (click)="goTo('destination')">Go TO DIV</a>
<div id='destination'>
<h2>Destination</h2>
</div>
Then in your component:
goTo(location: string): void {
window.location.hash = location;
}
Here's a very simple solution that worked for me:
In the component, add this method:
navigateTo(location: string): void {
// location will be a valid CSS ID selector; i.e. it should be preceded with '#'
window.location.hash = location;
setTimeout(() => {
document.querySelector(location).parentElement.scrollIntoView();
});
}
And in the view, the <a>
tag will look like this:
<a (click)="navigateTo('#destination')">Destination</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With