I'm trying to implement this "Scroll back to top" button found here:
https://www.w3schools.com/howto/howto_js_scroll_to_top.asp
I'm new to Angular and my attempts to implement this keep getting me errors and type errors.
This is my code:
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
}
}
I'm getting the errors:
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 also tried putting
window.onscroll = this.scrollFunction();
in ngOnInit like this:
ngOnInit(){
window.onscroll = this.scrollFunction();
}
but that doesn't work either.
How do I implement this? What did I do wrong and how do you fix it?
Well, it looks like the problem is that you try to declare a window property of your component by doing this:
export class HomeComponent {
// this code is not valid, because you try to declare a class property here, not to get the window reference
window.onscroll = this.scrollFunction();
}
Angular has a directive made specially for those purposes, called @HostListener
. I would recommend you to consider it.
@Component({...})
export class HomeComponent {
@HostListener('window:scroll', ['$event'])
onWindowScroll(event: Event) {
// do whatever you want here, including manipulations with the window object as it's available here
console.log(window);
}
}
Here is a reference to the official docs: https://angular.io/api/core/HostListener
Good luck:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.