带有Hashtag的Angular2路由到页面锚点 [英] Angular2 Routing with Hashtag to page anchor

查看:322
本文介绍了带有Hashtag的Angular2路由到页面锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在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/issues/6595

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

这篇关于带有Hashtag的Angular2路由到页面锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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