angular 10 scroll to element code example
Example 1: scroll to top angular
<router-outlet (activate)="onActivate($event)"></router-outlet>
export class AppComponent {
onActivate(event) {
window.scroll(0,0);
}
}
Example 2: on button click scroll to div angular
/?css or scss/
html {
scroll-behavior: smooth;
}
/?typescript/
private _vps: ViewportScroller
scrollFn(anchor: string): void{
this._vps.scrollToAnchor(anchor)
}
/?HTML/
<button (click)="scrollFn('about')">Scroll to div</button>
<div id="about">Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio, quasi nostrum labore sequi neque sed nihil consequuntur? Ea, dolorum minima,
cumque explicabo dicta est sit harum dolores, assumenda ex non.</div>
Example 3: scrollto angular
html {
scroll-behavior: smooth;
}
private _vps: ViewportScroller
scrollFn(anchor: string): void{
this._vps.scrollToAnchor(anchor)
}
<p on-click="scrollFn('about')">scroll to about sections</p>
<div id="about">Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio, quasi nostrum labore sequi neque sed nihil consequuntur? Ea, dolorum minima,
cumque explicabo dicta est sit harum dolores, assumenda ex non.</div>