简体   繁体   English

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

[英]How to make Angular `routerLink` fragment navigation scroll to my `id` target?

Can someone please help me to get the routerLink fragment scroll to work?有人可以帮我让routerLink片段滚动工作吗?

=> "Working" meaning that when I click on the routerLink, it does scroll to the element with the matching id. => “工作”意味着当我点击 routerLink 时,它会滚动到具有匹配 ID 的元素。 ;) ;)

Code example of what I did:我所做的代码示例:

<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>

Notes:笔记:

  • Both the co-trigger and the co-target are in the same template. co-triggerco-target都在同一个模板中。
  • Some co-target instances have enough content so that there is a scroll bar to make it meaningful to scroll to that item by clicking on the trigger.一些co-target实例有足够的内容,因此有一个滚动条,使通过单击触发器滚动到该项目有意义。
  • The url in the navigation bar changes as expected url#item-id , however no scroll happens when clicking on the trigger.导航栏中的 url 会按预期更改url#item-id ,但是单击触发器时不会发生滚动。

My AppRoutingModule setup:我的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 {
}

Context information:上下文信息:

Angular: 11.2.6

Any ideas on what I can do to get the " scroll to anchor target " functionality to work?关于我可以做些什么来使“滚动到锚定目标”功能起作用的任何想法?

为此,我使用了一个名为ngx-page-scroll的包。

You can use something like this.你可以使用这样的东西。

Step 1第1步

So each element you can define a method called scroll like this :因此,您可以像这样定义一个名为 scroll 的方法:

app.component.html应用程序组件.html

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

Step 2第2步

In the same component app.component.html define your section with an ID #home like this :在同一个组件app.component.html 中,使用ID #home定义您的部分,如下所示:

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

Step 3第 3 步

Now in the app.component.ts you can implement the scroll method like this :现在在app.component.ts 中,您可以像这样实现滚动方法:

scroll(el: HTMLElement) {

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM