Error encountered: Could not execute 'getComputedStyle' on the 'Window' object - the first parameter is not considered an 'Element' within the JavaScript map function

I've been searching for a solution to my problem both on StackOverflow and Google, but haven't been able to find one yet. So, here's my issue.

I have an array of DOM elements that I retrieve using the

@ViewChildren('labelSquare') public labelIcon: QueryList<HTMLSpanElement>;
decorator. In my HTML, I bind it as follows:

 <span class="status-item" *ngFor="let status of statusList">
     <div *ngIf="status.state !== 'Starting' &&
                 status.state !== 'Stopping' &&
                 status.state !== 'Synchronising' &&
                 status.state !== 'EmergencyStop'"
     >
       <div class="status">
         <span #labelSquare class="status-square fas fa-square {{ status.state }}"></span>
         <span class="status-name">{{ status.text }}</span>
       </div>
     </div>
 </span>

This generates an array of 58 span elements, and now I want to add a border with a color that is 10% darker than its current background. To achieve this, I am using a map:

if (this.labelIcon) {
     this.labelIcon.map((icon: HTMLSpanElement) => {
         const element = window.getComputedStyle(icon);
         icon.setAttribute('style', `border: 1px solid ${ColorUtil.darkenBorderFromBackground(element.color)}`);
     });
 }

In my

ColorUtil.darkenBorderFromBackground()
function, I simply return
return darken(${backgroundColor}, 10%)
. However, I encounter a
TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
.

Can someone provide some assistance?

Answer №1

In Angular, when you retrieve an ElementRef, it is not a direct reference to a DOM element.

The ElementRef object includes a property called nativeElement, which points to the actual DOM element. Therefore, make sure to replace instances of icon with icon.nativeElement inside the window.getComputedStyle() method.

Remember to update your TypeScript interface accordingly within the map function.

For example:

if (this.labelIcon) {
 this.labelIcon.map((icon: ElementRef) => { // Ensure that ElementRef is the correct interface in Angular
     const element = window.getComputedStyle(icon.nativeElement);
     icon.setAttribute('style', `border: 1px solid ${ColorUtil.darkenBorderFromBackground(element.color)}`);
 });
}

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

How come I am unable to track the total number of uploaded images while fetching them?

Within my vuejs2 app, I am facing an issue with uploading images selected in a modal form. The goal is to close the modal form only after all images have been successfully saved, triggering the self.hidePhotosUploadingModal() method. To keep track of the ...

What is the method for including a class in the anchor element that is the closest sibling of the containing ul element in the HTML structure?

I'm currently exploring traversal in jQuery and I'm a bit confused about how the class is being added to all the items in the unordered list. I know it's probably something simple that I'm missing. Any assistance would be greatly apprec ...

Retrieving information stored in local storage from a different path using Vuex

Using the config panel route, I am fetching data and setting it to local storage using Vuex and StoreJS: const state = { message: [], // console.log(message); sec: 0, // other state }; const getters = { message: ( ...

Manipulate and structure personalized date string using Moment.js

Trying to retrieve the month and year from a customized date string Wed Dec 24 00:00:00 -0800 2014 with Moment.js. Came across this previous solution: How to parse given date string using moment.js? however, the accepted answer is causing an error. Expec ...

Transforming a C statement to Java code: (Array[][] is not equal to 0)

While converting some C code to Java, I encountered an unfamiliar statement syntax that has left me puzzled about its meaning. for (unsigned int i = 0; i < SIZE; i++) { count[2 * SIZE + 1] += grid[i][SIZE - 1 - i] != 0; } During the process of add ...

Guide to generating a downloadable link using React and Express

In my React app, I have a button which is essentially a div. The Button Component returns this structure with all other elements as props: <button className={"button "+styleButton} onClick={handleClick}> {source && <img src= ...

Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question. My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's. Let&ap ...

Customizing Material-ui picker: concealing text field and triggering modal with a button click

I'm currently working with version 3.2.6 of the material-ui pickers library to develop a component that has different renderings for mobile and desktop devices. For desktop, I have set up a standard inline datepicker with a text input field, while fo ...

It seems that Ionic 2 does not support the registration of custom HTML tags

Encountering a problem with Ionic 2 and custom components. Developed a component to show in a list, serving as the list item. However, my app crashes when attempting to use the custom HTML tag. The stack trace is provided below. Uncertain about the issue. ...

Is it possible to generate React.js components using CDN links of our own creation?

My Next.js app features a Chatbot component that I want to make available for anyone to use on their own website by simply adding a script tag. If I place the component in my public folder for public access, how can I enable this functionality? I am looki ...

Tips for effectively integrating an admin panel into an Angular project

After building a website with Angular 6, I now need to develop an admin panel to make the site dynamic. What would be the best approach for this task - creating a separate Angular app for the admin panel or incorporating it within the existing website ap ...

Tips for transferring the ID from one element to another using JavaScript

I'm attempting to create a slideshow using icons all within one class. The "active" style class will have an ID and represent the current picture. By clicking either the left or right button, I aim to change the style of the active class. const l ...

It is necessary for the listener to be a function when handling a socket.io event

I decided to revamp my socket.io server to avoid the notorious "callback hell". Currently, I am exploring the option of listening for an event and passing a function exported by a module as the callback instead of using an anonymous function. My goal is t ...

Encountering difficulties posting an image with Ionic2/3 Social Share

Here, I am utilizing the Ionic social share feature to initially share an image. To achieve this, I am extracting the image using Canvas and then exporting the same image code to the share plugin. Upon doing this, the following data appears in my email bod ...

searching for a refined method to tackle this challenge

I'm relatively new to Angular and I'm interested in finding a more efficient solution for this particular task. The code below functions correctly, but I am uncertain if it is the best approach to achieve the desired outcome. HTML <div ng-a ...

Angular Alert: [$injector:modulerr] Unable to create the angularCharts module because: Error: [$injector:nomod]

Although this question has been asked multiple times, the standard solutions provided did not resolve my issue. Therefore, I am sharing my code along with the error in hopes that it will be self-explanatory. Error: Uncaught Error: [$injector:modulerr] Fa ...

Animating the scale of multiple objects in Three.js allows for dynamic and engaging visual

Hi there! I am new to three.js and currently going through various tutorials to master the art of animating 3D objects using three.js. As a result, you may find some parts of the code below to be familiar. My objective: I am looking for a way to gradually ...

Is there a way to disable the camera on React-QR-Reader after receiving the result?

My experience with react-qr-reader has been smooth for scanning QR codes, however, I'm having trouble closing the camera after it's been opened. The LED indicator of the camera remains on even when not in use. I attempted using the getMedia func ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Limiting the defaultValue of a select to one of the values of its options in TypeScript: A guide

Is there a way to configure the Select component's properties so that the defaultValue is limited to one of the predefined options values ("au" | "nz" in this scenario)? const countryOptions = [ { value: "au", l ...