我正在使用:
gotoAbout() {
this.router.navigate(['/'], { fragment: 'about' })
}
因为routerLink和a href="#about"会在我不在我的根/页面时重新加载我的页面。使用此函数在导航按钮上,它将在单击时导航到/#about而不重新加载页面,但问题是它根本没有像a href="#about"一样跳转到该div,当我从页面上滚动时。在Angular中有实现这个的方法吗?
我正在使用:
gotoAbout() {
this.router.navigate(['/'], { fragment: 'about' })
}
因为routerLink和a href="#about"会在我不在我的根/页面时重新加载我的页面。使用此函数在导航按钮上,它将在单击时导航到/#about而不重新加载页面,但问题是它根本没有像a href="#about"一样跳转到该div,当我从页面上滚动时。在Angular中有实现这个的方法吗?
goToDiv(fragment: string): void {
window.location.hash = fragment;
}
在模板中:
<a (click)="goToDiv('destination')">Go to div</a>
<div id='destination'>
<h2>Destination</h2>
</div>
编辑:正如@JB Nizet在评论中所述,您也可以尝试:
<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
link to user component
</a>
https://angular.io/docs/ts/latest/api/router/index/RouterLink-directive.html
this.router.navigate(['/results'], { fragment: 'top' });
- mickdev对于任何感兴趣的人,我的解决方案如下:
我的导航栏有一个名为“关于”的按钮,它的点击事件是 (click)="gotoAbout();" :
gotoAbout() {
let tree = this.router.parseUrl(this.router.url);
if (tree.fragment == 'about') {
let element = document.querySelector("#" + tree.fragment);
if (element) {
element.scrollIntoView(element);
}
}
else {
this.router.navigate(['/'], {fragment: 'about'})
.then( () => {
let tree = this.router.parseUrl(this.router.url);
let element = document.querySelector("#" + tree.fragment);
if (element) {
element.scrollIntoView(element);
}
});
}
}
- JB Nizet