[英]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:笔记:
co-trigger
and the co-target
are in the same template. co-trigger
和co-target
都在同一个模板中。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
实例有足够的内容,因此有一个滚动条,使通过单击触发器滚动到该项目有意义。url#item-id
, however no scroll happens when clicking on the trigger.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.