Guide on utilizing the "window" attribute within Angular framework

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?

Answer №1

Seems like you're encountering an issue where you're attempting to define a window property in your component using the following code:

export class HomeComponent {
  // This code is incorrect because you are trying to declare a class property instead of accessing the window reference
  window.onscroll = this.scrollFunction();
}

In Angular, there is a specific directive designed for this purpose called @HostListener. I suggest exploring this option.

@Component({...})
export class HomeComponent {
  @HostListener('window:scroll', ['$event'])
  onWindowScroll(event: Event) {
    // You can perform desired actions here, including working with the window object since it's accessible in this context
    console.log(window);
  }
}

For more information, refer to the official documentation at: https://angular.io/api/core/HostListener

Best of luck :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Binary stream (byte array) compatible video player for seamless playback

Is there a JavaScript/jQuery/HTML5 video player that can play a video without needing a physical file? I have a video file stored in a database (varbinary(MAX)) and I am looking for a player that can play the video using the byte array source. Has anyone ...

Organize a method's for-loop using JavaScript modules

I have a function that looks like this: function createModifiedList(people){ const modifiedList = [] for (let i = 0; i < people.length; i++){ modifiedList.push({ name: person.firstName + " " + person.lastName, ...

Selenium is encountering a validation error when selecting a value from a Drop Down menu

My current project involves automating website testing through selenium. I have encountered a scenario where I need to fill in a mandatory drop-down field. The code snippet I am using to select the drop-down value is as follows: select = Select(find_eleme ...

Is there a way to save the values of all input fields in a single container using local storage simultaneously?

Let's say I have the following structure: <div id="main"> <div id="wrapper"> <input/> <input/> <input/> </div> </div> My goal is to use localstorage to store the entire wrappe ...

merge various useState functions for appending values to an array into a unified function in a React component

I am currently facing a challenge with code complexity. I have 8 arrays where I need to add items based on a button click. As of now, I have created 8 separate functions for each task. Is there a way to consolidate all these functions into one function tha ...

What is the best way to implement auto-refreshing with reactQuery?

Hey there! I'm currently working with a GraphQL API and I'm trying to automatically refetch data at regular intervals (e.g. every 3 seconds). I've been using React Query and have tried some workarounds like using setInterval, but it's n ...

Angular 4 - dealing with request timeouts

I am having trouble implementing a request every second in my code as the timeout function is not working correctly. matchlist.service.ts import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/timeout'; getMatch(matchId: num ...

Exploring the Power of Jasmine Testing with Ternary Conditions

Imagine a scenario where we are working with the following snippet of JavaScript code. object = _.isUndefined(object) ? '' : aDifferentObject.property; Is it possible to write a Jasmine test that covers both scenarios? Do we need to use two se ...

Node.js now supports ES6 imports using the `--experimental-modules` flag,

Experimenting with ES6 imports in node using the -experimental-modules flag. Here are the steps: mkdir testfolder cd testfolder npm init npm i --save testing-library touch script.mjs Next, add the following code to script.mjs: import { test1, test2, tes ...

Showing the contents of an array which contains arrays

Retrieves the elements stored in the history array. Each element of the history array is a separate array containing fields with names and values. The goal is to display this history table by iterating over each element of the array and displaying it in ...

Tips for displaying "No Results" without causing any lag in the browser

I'm encountering difficulty trying to implement a simple feature without resorting to a "messy" solution. The performance is suffering, and I am certain it's not done in a "professional" manner. What I desire is straightforward – displaying a ...

Utilizing Firebase objects across multiple files: A comprehensive guide

I apologize for my ignorance, but as I am teaching myself, I have not been able to find the answer in the available documentation. My current project involves developing a Vue application with Firebase as the backend. To utilize Firebase services, you mus ...

What is the best way to extract data from a nested array within an array of objects and transfer it to a separate array without altering its nested arrangement?

I have a collection of different objects stored in an array. Each object within the main array contains another array with specific details like this: const data = [ { id: 1, name: "Jack", interests: [ ...

The request to retrieve data from the model at http://localhost:9000/model/data.json resulted in a 404

This is the path to my directory I have a npm server running on http://localhost:9000/ to utilize the cytoscape module. However, my server is unable to locate my json file. What could be the issue with my code? This is the source code of my index.js file ...

Tips for dynamically passing a string into a Javascript function

Here is a JavaScript function that I have: function doIt(link) { alert(link); } I am using this function in the following JavaScript code snippet. Here, I am dynamically creating an anchor tag and appending it to my HTML page: jQuery.each(data, func ...

Waiting for the HTTP response in NodeJS before sending the next request

I'm currently struggling with my NodeJS code. I am attempting to send an HTTP Request to a REST API, which will respond with a new URL. Once I receive this URL, I need to make another request to that specific URL and continue the process. My current ...

Is it beneficial to create two distinct node applications—one to serve a webservice and another to consume that webservice in order to display it on a browser?

Is it more efficient to run two separate node instances for different purposes (webservice engine/data engine and webservice consumer), or is it better to combine both functions in the same application? ...

Integrating a spinner into a React component

I am currently working on implementing a loader for my react component. The idea is that when the background image is loading, it should display 'loading', and once it has finished loading, it should display 'loaded' To test the loader ...

Tips for choosing a selection of items using the mouse (such as a calendar date range picker)

I have a simple question. I am creating a full calendar using Jquery and I would like to know how to achieve a functionality that is illustrated in the images below. When the user selects day 3 of the month (it will appear as blue) and hovers over day 8, a ...

How can I configure Express to act as a pass-through proxy server?

How can I set up an express server to act as a proxy? Requirements: Support for both http and https Ability to function behind a corporate proxy Option to provide custom content for specific URLs I have experimented with various modules such as http-pr ...