Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Hashtag routing to Anchor doesnt move page

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.

like image 818
jipson Avatar asked Aug 10 '16 15:08

jipson


2 Answers

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;
}
like image 110
JohnMAC Avatar answered Nov 01 '22 13:11

JohnMAC


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>
like image 3
Soma Mbadiwe Avatar answered Nov 01 '22 12:11

Soma Mbadiwe