带有标签的Angular2路由到页面锚点 [英] 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路由到页面锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!