По умолчанию прокрутка привязки не включена в Angular Router (после v.6.1.0).
Вы можете включить его, импортировав RouterModule следующим образом:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled'
})
Док: https://angular.io/api/router/ExtraOptions#anchorScrolling
Ваш якорь будет идентификатором div.
Использование
HTML:
<a [routerLink]="['somepath']" fragment="customer">Jump to 'customer' anchor </a>
TS:
this.route.fragment.subscribe(f => {
console.log("f ", f);
const element = document.querySelector("#" + f)
if (element) element.scrollIntoView()
});
Другие решения.
Вы можете использовать динамическую прокрутку.
<div #customer>Customers</div>
<button (click)="scrollToElement(customer)">Scroll</button>
.
И в вашем файле ts:
scrollToElement(el) {
el.scrollIntoView();
}
Или
использовать ViewChild:
@ViewChild("customer") customerElement: ElementRef;
this.customerElement.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
Или используйте угловую библиотеку, например:
https://www.npmjs.com/package/@nicky-lenaers/ngx-scroll-to