Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Router: add hashtag to url

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.

like image 342
punov Avatar asked Jan 07 '23 08:01

punov


2 Answers

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})]);
like image 184
lame_coder Avatar answered Jan 16 '23 03:01

lame_coder


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?

like image 26
Daniel Kettemann Avatar answered Jan 16 '23 04:01

Daniel Kettemann