Updated on Kisan Patel
Let’s learn how to scroll specific element on click in Angular?
Solution 1:
app.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'scroll', template: ` <button (click)="scroll(target)">Click to scroll</button> <div #target>Your target</div> `, styles: [`h1 { font-family: Lato; }`, `div { margin-top: 5000px; }`] }) export class ScrollComponent { scroll(el: HTMLElement) { el.scrollIntoView(); } }
Solution 2:
if you want to scroll specific element from another page.
app.component.html <a [routerLink]="['/contact-us']" fragment="destination" class="btn btn-warning text-dark font-weight-bold mr-0 py-2">Destination</a>
contact-us.component.html
<section>
</section>
..
<section class=”section section-md position-relative overflow-hidden” #destination>
</section>
contact-us.component.ts
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-contact-us', templateUrl: './contact-us.component.html', styleUrls: ['./contact-us.component.css'] }) export class ContactUsComponent implements OnInit, AfterViewInit { @ViewChild('destination') destination: ElementRef<HTMLElement>; constructor( private route: ActivatedRoute) { } ngAfterViewInit() { this.route.fragment.subscribe( (fragments) => { if(fragments == "destination"){ this.scrollToDestination(); } } ); } scrollToDestination() { this.destination.nativeElement.scrollIntoView(); } }