【问题标题】:Scroll to given place on init based on the route根据路线滚动到init上的给定位置
【发布时间】:2016-10-07 15:16:50
【问题描述】:

我的页面上一个接一个地有几个组件,例如:

<about></about>
<contact></contact>

等等

当导航链接被点击时,我正在使用ng2-page-scroll 滚动到给定部分,但我无法在应用程序初始化时滚动到给定部分。

所以当用户第一次打开带有/contact 的页面时,它会在初始化时向下滚动到联系人,而不是停留在顶部。

我用

if(this.router.url != '/') {
  let pageScrollInstance: PageScrollInstance = PageScrollInstance.simpleInstance(this.document, '#'+this.router.url.substring(1));
  this.pageScrollService.start(pageScrollInstance);
}

在构造函数内部,但在路由器在router.url 上设置路由之前触发

我已经设法将它与window.location.href.split("/").pop() 一起正常使用,以在设置路由器之前获取地址,但这发生在组件实际呈现之前并且它滚动到错误的位置。

是否有一个钩子会在整个应用设置路由后触发一次?

【问题讨论】:

  • ngOnInit() 内尝试。有什么问题吗?
  • @micronyks 是的。 the router.url 与预期不符 + 未加载整个内容,因此滚动到错误位置

标签: javascript angular typescript


【解决方案1】:

有了这个,您可以将NavigationEnd url 存储到任何变量(服务中)并在您的应用程序中使用它。

这可以用于(在AppComponent中)触发url之间的变化。

router.events.subscribe(event => {
      //if (event instanceof NavigationStart) {
        console.log('event', event)
      //}
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2015-10-11
    相关资源
    最近更新 更多