Angular2 Routing with Hashtag to page anchor [英] Angular2 Routing with Hashtag to page anchor

查看:16
本文介绍了Angular2 Routing with Hashtag to page anchor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我的 Angular2 页面上添加一些链接,当点击这些链接时,将跳转到该页面的特定位置,就像普通标签所做的那样.所以链接将类似于

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

我认为我不需要 HashLocationStrategy,因为我对正常的 Angular2 方式没问题,但是如果我直接添加,链接实际上会跳转到根目录,而不是同一页面上的某个地方.任何方向表示赞赏,谢谢.

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.

推荐答案

更新

现在支持

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>

this._router.navigate( ['/somepath', id ], {fragment: 'test'});

将下面的代码添加到您的组件中以滚动

  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) { }
  }

原创

这是一个已知问题,可在 https://github.com/angular/angular/进行跟踪问题/6595

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

这篇关于Angular2 Routing with Hashtag to page anchor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆