Scroll to anchor not working

2020-02-27 09:32发布

问题:

Trying to scroll to an anchor link using the following syntax.

<a [routerLink]="['./']" fragment="test">Testing</a>

And the anchor node looks like this

<div id="test">

When clicked the browser address bar shows the #test fragment but the automatic scrolling does not occur. Any idea why it does not scroll?

回答1:

Based on @vsavkin workaround and taking advantage that fragments are provided as an observable (using "@angular/core": "^2.3.1"):

class MyAppComponent implements OnInit{

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.fragment.subscribe(f => {
      const element = document.querySelector("#" + f)
      if (element) element.scrollIntoView()
    })
  }
}


回答2:

I suppose scrolling isn't implemented with angular 2 yet. My solution to similar problem (scrolling to anchor on the same page) was to use ng2-page-scroll.



回答3:

Look in Angular 6 new feature ViewportScroller

https://angular.io/api/common/ViewportScroller



回答4:

From Angular 6.1 there is anchorScrolling for the router:

  1. Set this in app.module.ts

       imports: [
         RouterModule.forRoot(routes, {
           scrollPositionRestoration: 'enabled', // or 'top'
           anchorScrolling: 'enabled',
           scrollOffset: [0, 64] // [x, y] - adjust scroll offset
         })
       ],
       exports: [RouterModule]
    
  2. html

     <div id="test">
       // contents goes here...
     </div>
    
    
    
     <a [routerLink]="['./']" fragment="test">Testing</a>
    
  3. Import now the viewScroller which Angular v6 new feature (this might be not neccesary):

     import { ViewportScroller } from '@angular/common';
    
     constructor( private viewportScroller: ViewportScroller ) 
    
     ...
    
     scrollToTest() { 
       this.viewportScroller.scrollToAnchor('test');
     }
    


回答5:

I can suggest to user ng2-page-scroll

ng2-page-scroll

install

npm install ng2-page-scroll --save

import in your app.module.ts

import {Ng2PageScrollModule} from 'ng2-page-scroll';

@NgModule({
    imports: [
        /* Other imports here */
        Ng2PageScrollModule
        ]
})
export class AppModule {
}

test it in your html component

<a pageScroll href="#test">Testing</a>
<div id="test">


回答6:

I liked using this

scroll(container, target) {
    let scrollTo = target.getBoundingClientRect().top;

    $(container).animate({
      scrollTop: `+=${scrollTo}`
    }, 900);
}

then in HTML do something like

<div #container> <!-- Scrolling container -->
    <button (click)="scroll(container, intro)">Go To Intro</button>
    <!-- other content -->
    <div #intro></div>
</div>


标签: angular