Recently, I came across a neat "Scroll back to top" button that caught my eye:
https://www.w3schools.com/howto/howto_js_scroll_to_top.asp
Despite being new to Angular, I wanted to give it a try and implement this feature myself. However, every attempt I make results in errors and type mismatches.
This is the code snippet I have been working on:
home.component.html
<div class="country-card-container">
<button (click)="topFunction()" class="scroll-top">TOP</button>
<app-country-card *ngFor="let country of displayCountries" [country]="country" class="country-cards"></app-country-card>
</div>
home.component.ts
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent {
mybutton = document.getElementsByClassName("scroll-top");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = this.scrollFunction();
scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
this.mybutton.style.display = "block";
} else {
this.mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
}
Encountering these errors has been quite frustrating:
Unexpected keyword or identifier.ts(1434)
Member 'window' implicitly has an 'any' type.ts(7008)
Cannot find name 'scrollFunction'.ts(2304)
Property 'style' does not exist on type 'HTMLCollectionOf<Element>'.ts(2339)
I even attempted moving
window.onscroll = this.scrollFunction();
into the ngOnInit section like so:
ngOnInit(){
window.onscroll = this.scrollFunction();
}
Unfortunately, that didn't solve the issue either.
If anyone could guide me on the right path for successful implementation, I would greatly appreciate it. What mistakes did I make and how can they be rectified?