Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help.

I recently started delving into TypeScript due to my work with Angular. I managed to access a group of controls within the DOM and then proceeded to select one of them along with its children.

@ViewChildren("marker") markers: QueryList<ElementRef>;

this.markers.forEach(item => {
  let element = item.nativeElement;

  //item.children.forEach(child => {child.classList.add("poof"); });
  for (let child of element.children)
    child.classList.add("poof");
});

When looking at the console, it appears as an array due to the brackets, even though typeof indicates it is an object.

I'm currently confused about this issue and also curious as to why the commented out code does not seem to be working. Unfortunately, I am unsure of what to search for to gain more insight into this matter.

Answer №1

When dealing with arrays in TypeScript, it's important to remember that TypeScript only recognizes and allows methods that are defined for that type. For instance, if you have a type QueryList<> that behaves like an array at runtime, TypeScript may not be aware of it.

To work around this issue, you can opt for using the for..of loop instead of forEach. Alternatively, you can extend QueryList<> to Array<T> in order to continue utilizing the forEach method.

Answer №2

The method forEach is a part of the Array prototype, meaning it can only be used on variables that are classified as Arrays.

In Angular documentation (found here), it states that QueryList type follows the Iterable interface, allowing for looping using for ... of.

It's important to note that the output displayed in the Google Chrome console (or any other browser) may not accurately represent the true nature of an object.

Answer №3

Before implementing any changes, be sure to wait for the markers to finish rendering in the view:

@ViewChildren("marker") markers: QueryList<ElementRef>;

 ngAfterViewInit() {
     this.markers.forEach(item => {
     let element = item.nativeElement;

    //item.children.forEach(child => {child.classList.add("poof"); });
    for (let child of element.children)
      child.classList.add("poof");
    });
}

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

AngularJS fails to recognize Iframe element during REST request

I'm having trouble with my webpage only reading the Iframe tag. It's sending the content correctly according to Postman. Postman is giving me this content: "Conteudo": "<p>Test iframe:</p>\n\n<p><iframe framebord ...

Verify if a specific key is present in associative arrays

Can you please explain the correct way to check for the existence of a key in associative arrays? For instance: var mydata = { key1: '', key2: { subkey1: { subkey1_1: { value1: '' ...

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

Verifying changes using Cypress transformations

I'm brand new to using Cypress and I am currently attempting to verify that one of my elements contains a specific style. The element in question looks like this: <div class="myElement" style="transform: translate(0%, 0px); "></div> Her ...

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

Prevent Chrome extension from triggering HTTP authentication popup (digest)

Currently in the process of developing a chrome extension that requires access to http-auth protected resources (webdav), particularly those using digest authentication. I have successfully implemented authentication directly within the ajax request by ut ...

What is the best way to update the $scope of a directive from another directive's controller in Angular.js?

One of my directives is responsible for loading a list of events from a service: .directive('appointments', [function () { return { restrict: 'CE', scope: { ngTemplate: '=', ...

Trouble occurs when parsing a JSONArray

I am new to the Android world and I am attempting to retrieve a JSONArray from the following URL: Here is my TabHostExample.java code: public class TabHostExample extends TabActivity { private static String url = "http://www.softmarketing.it/json/view/a ...

Utilizing AJAX to fetch API data and leveraging jQuery to iterate through intricately nested JSON data structures

I've implemented AJAX to connect to an API that returns a JSON object (see the JSON code reference below) and I'm trying to iterate through and parse the JSON data to display inside an HTML element. Although everything else in my code is functio ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

While attempting an AJAX request with jQuery, I encountered the following error message: "Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN"

I encountered an issue that says: ` throw err; // Rethrow non-MySQL errors ^ Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN ` while attempting a jQuery AJAX get request, and I'm unsure of the cause. My backend is built using node.js a ...

AngularJS - Move the <li> element to the top when its corresponding checkbox is selected

This particular question pertains to a topic that was previously discussed in another thread The scenario involves using a ng-repeat as shown below: <li ng-repeat="opt in namesCtrl.uniqueCars"> <input type="checkbox" ng-model="namesCtrl.filt ...

How can I assign integer values to specific child elements after splitting them?

Below is the HTML code that needs modification: <div class="alm-filter alm-filter--meta" id="alm-filter-1" data-key="meta" data-fieldtype="checkbox" data-meta-key="Cate" data-meta-compare="IN" data-meta-type="CHAR"> <ul> <li class=" ...

Discovering duplicated arrays within a sequence

I am facing an issue with my Python code. I have a list containing approximately 131,000 arrays, each with a length of 300. My goal is to identify which arrays are repeating within this list by comparing each array with the others. Here is what I have trie ...

react-data-table-component establishes the structure of the expanded element

Has anyone encountered an issue with the react-data-table-component? I need to pass a row type (typescript model) to the Detail component that is rendered when the row is expanded. Detail: export const Detail = (row: certificates) => { //it works fine ...

I encountered an issue with the mui TextField component in React where it would lose focus every time I typed a single character, after adding key props to

I'm encountering an issue with a dynamic component that includes a TextField. Whenever I add the key props to the parent div, the TextField loses focus after typing just one character. However, when I remove the key props, everything works as expected ...

Click once to expand all rows in the table with ease

I have successfully created a basic table using HTML. The table includes nested elements that are designed to open individually when clicked on the assigned toggle. Essentially, clicking on a '+' icon should reveal a sub-menu, and clicking on a & ...

What is the reason behind the quicker search for the median in a 100-item array compared to a 10-item array?

I conducted experiments to verify this, and the results were not entirely as anticipated: http://jsperf.com/value-in-array-or-object Feel free to run your own tests as well. ...

I can't seem to retrieve any values from the API other than "chicken"

Is there a way to make the search bar in my recipe app look for recipes that I provide, rather than fetching data from useState? Any suggestions on how I can achieve this? import React, { useEffect, useState } from 'react'; import Recipe from &ap ...

Interested in using jQuery to trigger the f12 key press?

In my current project, I have successfully disabled the f12 and right click using jQuery. Here is the code snippet: $(document).keydown(function(event){ if(event.keyCode==123){ return false; } else if(event.ctrlKey && event.shiftKey && ...