4

I'm using Angular2 Seed application, and you can find it in the official repo. As you can see, here we have angular2/router imported, and we're using it to create the basic routing of the application.

import {Component, ViewEncapsulation} from 'angular2/angular2';
import {
  RouteConfig,
  ROUTER_DIRECTIVES
} from 'angular2/router';
...
@RouteConfig([
  { path: '/', component: HomeCmp, as: 'Home' },
  { path: '/about', component: AboutCmp, as: 'About' }
])
export class AppCmp {}

My question is: how can I configure router to add hashtag in my url, to make it looks like: localhost:5555/#/about. Is there any beautiful and easy way to make it? (as earlier with $locationProvider)

I know it's bizarre, but I used to love this hashtag in url, and my apache-config also used to love it. Of course, I can change my httpd.conf file, very easy and properly, but I really want to figure out, how to simply add hashtag, with Angular2 Router.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
punov
  • 798
  • 7
  • 16

2 Answers2

7

In your application startup file, you need to provide locationstrategy while calling bootstrap,

import {LocationStrategy, HashLocationStrategy} from 'angular2/router';

class MyDemoApp {
    //your code
}

bootstrap(MyDemoApp,[provide(LocationStrategy, {useClass: HashLocationStrategy})]);
lame_coder
  • 3,085
  • 3
  • 19
  • 21
  • 1
    It seems it is located under '@angular/common' now. https://angular.io/docs/ts/latest/api/common/index/HashLocationStrategy-class.html – Enis May 30 '17 at 09:56
1

For anyone with the same problem, but not using Angular Seed:

navigateToSomeLocation(location: string){
  window.location.href = "#" + location;
}

if you use Angular Material and you want to subscribe to the scroll event to change the url (like here: https://material.io/design/navigation/understanding-navigation.html#), subscribe to the ScrollDispatcher:

constructor(public scrollDispatcher: ScrollDispatcher) {
  this.scrollingSubscription = this.scrollDispatcher.scrolled()
      .subscribe((data: CdkScrollable) => {
        console.log(window.pageYOffset);

  });
}

and then check the if the user is scrolling over the anchor:

elem = document.getElementById('someHTMLElement') as HTMLElement;
distance = elem.getBoundingClientRect().top;

if (distance < 30 && distance > -30) {
    this.navigateToSomeLocation(elem.id);
  }

for reference see: Change url when manually scrolled to an anchor?