I have recreated an reusalbe service that can be used in any component in order to either scroll to fragment if present else to top of the page.The following contains the complete echo system in angular anchoring use through reusable service approach.
//(In service.ts)
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ViewportScroller } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class RouterPathService {
constructor(
private activatedRoute: ActivatedRoute,
private viewportScroller: ViewportScroller,
) { }
scroll() {
this.activatedRoute.fragment.subscribe((fragment: string) => {
if (fragment) {
this.scrollToAnchor(fragment)
} else {
this.scrollToTop();
}
});
}
scrollToTop() {
this.viewportScroller.scrollToPosition([0, 0])
}
scrollToAnchor(elementId: string): void {
this.viewportScroller.scrollToAnchor(elementId);
}
}
We can call function from above reusable service from any component as :
//(In component.ts)
......
constructor(
private routerPathService: RouterPathService,
) {
this.routerPathService.scroll();
}
....
HTML component would like :
<a [routerLink]="['/my-route']" fragment="test">Testing</a>
And app-routing.module.ts should enable the anchoring as:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
.........
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
anchorScrolling: 'enabled',
})],
exports: [RouterModule]
})
export class AppRoutingModule { }