Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Dynamically changing URL (in the address bar)

I came across this behaviour in the ESPN website and was wondering how to achieve that using Angular2. When I am reading an article there, as soon as the article is done, the next article loads and the URL in the address bar changes automatically. Once I scroll back up to the old article, the URL changes again to the old one. For example, take this link.

http://www.espn.in/football/barclays-premier-league/23/blog/post/3017450/phil-jones-and-henrikh-mkhitaryan-in-team-of-the-weekend

This is just a random article from the site. You can check the behavior mentioned above there. I also saw that the ESPN website was not built with Angular 2.

Still, I was just wondering if I wanted to do this using Angular2, how do I proceed? That is, to change the URL in the address bar on scrolling through a page or something to that effect.

like image 720
Srikkant Srinivasan Avatar asked Dec 12 '16 10:12

Srikkant Srinivasan


3 Answers

In case anyone is still looking to solve this.

This is what I ended up doing then. Going through the documentation, I realised that when a router navigates to a route that renders the same component, the component isn't initialised again.

Let us say you have this route that renders the ItemComponent.

item/:id

When you are navigate like this.

item/3 -> item/4

The component does not get initialised again. I leveraged this and depending on my current position in the page, I navigated to the URL I wanted in the address bar. It does not sound entirely convincing, but it does work.

like image 178
Srikkant Srinivasan Avatar answered Nov 02 '22 07:11

Srikkant Srinivasan


You'd have two choices, using hash ( # ) or not using it :).

In order to not use the hash, you'd need to tell your server to re-route all the request to index.html otherwise it won't work.

And you'd need to say :

 RouterModule.forRoot( ROUTES , { useHash : false } )
like image 26
Milad Avatar answered Nov 02 '22 07:11

Milad


You can manipulate the current anchor as you want in Javascript without reloading the page. So, when you're setting your url with :

location.href = location.href+ "#1234";   

You won't reload the page until "1234" means something for the router.

like image 30
Karbos 538 Avatar answered Nov 02 '22 09:11

Karbos 538