2017-02-28 30 views
2

我使用:角2相当于A HREF = “#someElementId”

gotoAbout() { 
    this.router.navigate(['/'], { fragment: 'about' }) 
} 

因为routerLink和A HREF = “#关于” 重新加载我的网页,如果我不是我的根/页。在导航按钮上使用这个功能,它将在一次点击后导航到/#关于无需重新加载页面,但问题是它不是跳跃到那个div,就像我滚动离开它时一样href =“#about”在页面上。有没有办法实现这个角度?

回答

0

任何有兴趣,我的解决方案去如下:

我的导航栏有一个 '约',这(点击)按钮= “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); 
      } 
     }); 
    } 
    } 
0

这似乎有点哈克,但它的工作原理:

在你的组件

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

+0

哈克是好的,但将这goToDiv工作之前,我的(点击)路由器,带我到/#关于哪个导致我的身体页面显示约div,所以div不会在DOM上呈现,直到路由完成 – seanEd

+0

你可以捕获片段并在Init处运行goToDiv()。编辑:根据文档,你可以用这样的东西做得更好:'this.router.navigate(['/ results'],{fragment:'top'});' – mickdev

+0

我使用这个组件来读取片段从ActivatedRoute来确定要显示几个选项之间的内容,如果我没有这样做,这将工作:P我现在尝试你的gotodiv解决方案 – seanEd