简体   繁体   中英

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?

=> "Working" meaning that when I click on the routerLink, it does scroll to the element with the matching 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.
  • 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.
  • The url in the navigation bar changes as expected url#item-id , however no scroll happens when clicking on the trigger.

My AppRoutingModule setup:

@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

So each element you can define a method called scroll like this :

app.component.html

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

Step 2

In the same component app.component.html define your section with an ID #home like this :

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

Step 3

Now in the app.component.ts you can implement the scroll method like this :

scroll(el: HTMLElement) {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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