How to smooth scroll to page anchor in angular 4 without plugins properly?
AngularTypescriptScrollRoutesAngular Problem Overview
What I want to achieve is a click to and do a smooth scroll to bottom / specified div area which i define with hashtag just like
i think it should be like this.here is the live example in the w3school example which is written for JQuery: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll
What I do is peek from this answer: https://stackoverflow.com/questions/36101756/angular2-routing-with-hashtag-to-page-anchor
but i don't really understand the answer, the answer is looked like this :
this part is HTML part :
<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
and below this, the router.navigate is where should I put the code? component.ts right? but how do i access this function? should i implement (click)?
this._router.navigate( ['/somepath', id ], {fragment: 'test'});
and below this, i get it, which it should write in my component.ts :
** Add Below code to your component to scroll**
import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import
private fragment: string;
constructor(private route: ActivatedRoute { }
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}
ngAfterViewInit(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}
what is the "somepath" mean? I should add a route in my routes.ts right? usually, i add a new path in here for example like this :
export const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'product', redirectTo: '/product' },
...homeRoutes,
...productRoutes
];
can anyone provide me with full example code in HTML, routes, and component?
Angular Solutions
Solution 1 - Angular
I was looking for a similar solution and tried to use the ngx-scroll-to package and found that its not working in latest version of angular (angular 6+) so decided to look into other option and found a solution which uses the browser's native scrollIntoView
and this seems to be the best solution so far
HTML code :
<button (click)="scrollToElement(target)"></button>
<div #target>Your target</div>
Ts code :
scrollToElement($element): void {
console.log($element);
$element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
Solution 2 - Angular
CSS only solution
html {
scroll-behavior: smooth;
}
It works even after navigation or page reload.
Please note that it does not work in IE, Edge or Safari.
Solution 3 - Angular
You can simply do this in your component.
const element = document.querySelector("#destination")
if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' })
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Solution 4 - Angular
In new Angular versions the solution is:
component.html
<p (click)="scrollTo()">scroll</p>
.
.
.
<form id="myForm">
.
.
.
</form>
component.ts
constructor(private viewportScroller: ViewportScroller) {}
scrollTo() {
this.viewportScroller.scrollToAnchor('myForm');
}
your-general-styles.css
html {
scroll-behavior: smooth;
}
Solution 5 - Angular
I just used ngx-page-scroll. It can be as simple as:
<a class="nav-link nav-item-text" pageScroll href="#categories">Categorias</a>
....
<section id="categories">
Visit the package page for more information: https://www.npmjs.com/package/ngx-page-scroll
It also provides mechanisms to configure scrolling process, or event implement custom behavior through a service that controls the scrolling from the component's controller.
Solution 6 - Angular
// you can use ViewportScroller calss
constructor(
private viewPortscroller: ViewportScroller
) {}
scrollingTop() {
this.viewPortscroller.scrollToPosition([0 , 0]);
}
// and for smoothly scroll you can do that
html, body {
height: 100%;
scroll-behavior: smooth;
}
Solution 7 - Angular
you have to add the flowing:
1- in app-routing.module.ts
:
@NgModule({
imports: [RouterModule.forRoot(routes,
{
useHash: true,
scrollPositionRestoration: 'top',
anchorScrolling: 'enabled',
scrollOffset: [0, 64],
relativeLinkResolution: 'legacy'
}
)],
exports: [RouterModule]
})
export class AppRoutingModule { }
2- in style.scss
:
body, html {
overflow-x: hidden;
scroll-behavior: smooth !important;
}
3- in the .html
file :
<li>
<a routerLink="home">Home</a>
</li>
<li>
<a routerLink="." fragment="about">About</a>
</li>
OR like this:
<div class="mt-4">
<a class="main-button" style="margin-left: 0px;" routerLink="." fragment="testimonials">
testimonials
</a>
</div>
Solution 8 - Angular
Try removing the square brackets:
class="startScroll" scrollTo="'#firstDiv'" scrollBoxID="'#scrollBox'"
Solution 9 - Angular
I got it work by doing this, consider that top-page is the id that you want to scroll to.
document.getElementById("top-page").scrollTo({ behavior: "smooth", top: 0 });
Solution 10 - Angular
you could use css with this :
html {
scroll-behavior: smooth;
}
Solution 11 - Angular
document.getElementById("top-page").scrollIntoView({ behavior: "smooth" });
Solution 12 - Angular
Add the below lines in style.css to get nicescroll in your angular application page.
::-webkit-scrollbar {
width: 5px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
background: #c3c3c3 !important;
}