Angular2 Router: add hashtag to url

大兔子大兔子 提交于 2019-12-05 23:58:31

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})]);

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!