如何使 Angular `routerLink` 片段导航滚动到我的 `id` 目标?

问题描述 投票:0回答:3

有人可以帮我让

routerLink
片段滚动正常工作吗?

=> “正在工作”意味着当我单击 routerLink 时,它会滚动到具有匹配 id 的元素。 ;)

我所做的代码示例:

<co-trigger routerLink="." [fragment]="item?.id" *ngFor="let item of items">Trigger</co-trigger>
...
<co-target [attr.id]="item?.id" *ngFor="let item of items">Target</co-target>

备注:

  • co-trigger
    co-target
    都在同一个模板中。
  • 一些
    co-target
    实例有足够的内容,因此有一个滚动条,可以通过单击触发器滚动到该项目。
  • 导航栏中的 URL 按预期更改
    url#item-id
    ,但是单击触发器时不会发生滚动。

我的

AppRoutingModule
设置:

@NgModule({
  imports: [
    RouterModule.forRoot(
      routes,
      {
        onSameUrlNavigation: 'reload',
        anchorScrolling: 'enabled',
        scrollPositionRestoration: 'enabled',
        scrollOffset: [0, 64], // [x, y] - adjust scroll offset
      }
    ),
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

上下文信息:

Angular: 11.2.6

关于如何让“滚动到锚定目标”功能发挥作用,有什么想法吗?

angular scroll navigation routerlink angular-routerlink
3个回答
0
投票

我使用名为 ngx-page-scroll 的包来实现此目的。


0
投票

你可以使用这样的东西。

步骤1

因此,您可以为每个元素定义一个称为滚动的方法,如下所示:

app.component.html

<a class="nav-link" (click)="scroll(home)">Link Name</a>

第2步

在同一个组件中 app.component.html 使用 ID #home 定义您的部分,如下所示:

<section #home>
...
</section>

第3步

现在在 app.component.ts 中,你可以像这样实现滚动方法:

scroll(el: HTMLElement) {

  el.scrollIntoView({ behavior: 'smooth' });

}

0
投票

作为替代方案,您可以使用新的 api ViewportScroller

示例取自此处

constructor(private readonly scroller: ViewportScroller) { }

this.scroller.scrollToAnchor(value); /*value:bottomLink*/

//html
<a href="##" id="bottomLink">bottom</a>

或滚动到特定的 px 值

this.scroller.scrollToPosition([0, 500]); /*x0px: y:500px*/
© www.soinside.com 2019 - 2024. All rights reserved.