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: 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?
If you press the mouse scroll wheel, you can move your mouse up/down and the scroll will be very smooth. Enabling a smooth scroll allows you to scroll like that with your regular wheel scroll. Smooth scrolling is also useful with keyboard shortcuts.
smooth. Allows a smooth animated "scroll effect" between elements within the scrolling box. initial. Sets this property to its default value. Read about initial.
The scroll-behavior property in CSS allows us to define whether the scroll location of the browser jumps to a new location or smoothly animates the transition when a user clicks a link that targets an anchored position within a scrolling box. html { scroll-behavior: smooth; }
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"}); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With