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?
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()
})
}
}
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.
Look in Angular 6 new feature ViewportScroller
https://angular.io/api/common/ViewportScroller
From Angular 6.1 there is anchorScrolling
for the router:
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]
html
<div id="test">
// contents goes here...
</div>
<a [routerLink]="['./']" fragment="test">Testing</a>
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');
}
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">
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>