javascript - 根据路线滚动到 init 上的给定位置

标签 javascript angular typescript

我的页面上有几个组件相继出现,例如:

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

等等

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

因此,当用户第一次打开路由中包含 /contact 的页面时,它会在 init 上向下滚动到 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() 来获取地址,但这发生在组件之前实际上已渲染并且滚动到错误的位置。

是否有一个钩子(Hook)在设置了整个应用程序的路由后触发一次?

最佳答案

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

这可以用来(在AppComponent中)触发网址之间的更改。

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

关于javascript - 根据路线滚动到 init 上的给定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39920654/

相关文章:

javascript - 如何在 Typescript 中使用正则表达式进行电子邮件验证

reactjs - 类型 'Provider<AnyAction>' 丢失

typescript - 使用声明文件覆盖 Cypress typescript

javascript - 谷歌海拔没有 map 显示

javascript - 如何在 d3 VERSION 4 中获取相对于元素原点的 (x, y) 坐标

javascript - ES6中如何删除数组中的对象

javascript - 更新 URL 而不触发状态更改

angular - 你怎么知道你需要什么样的包版本?

json - 错误 TS2339 : Property 'results' does not exist on type 'Response'

javascript - Sidenav 抛出异常 : Error during evaluation of "onShown"