Angular2 Routing with Hashtag to page anchor

Stone picture Stone · Mar 19, 2016 · Viewed 109.9k times · Source

I wish to add some links on my Angular2 page, that when click, will jump to specific positions within that page, like what normal hashtags do. So the links would be something like

/users/123#userInfo
/users/123#userPhoto
/users/123#userLikes

etc.

I don't think I need HashLocationStrategy, as I'm fine with the normal Angular2 way, but if I add directly, the link would actually jump to the root, not somewhere on the same page. Any direction is appreciated, thanks.

Answer

Günter Zöchbauer picture Günter Zöchbauer · Mar 19, 2016

Update

This is now supported

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
this._router.navigate( ['/somepath', id ], {fragment: 'test'});

Add Below code to your component to scroll

  import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import

  private fragment: string;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector('#' + this.fragment).scrollIntoView();
    } catch (e) { }
  }

Original

This is a known issue and tracked at https://github.com/angular/angular/issues/6595