0

I know how to use forEach in general but today I hit a spot that puzzled me. I've googled it but didn't get anything that I didn't already know.

I'm starting with TypeScript because of Angular and I've accessed a set of controls from the DOM. Then, I pick one of them and get to 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");
});

According to the console, it looks like an array, as it's a list with brackets (although typeof tells me it's an object).

I'm confused about this and curious about why the commented out code doesn't work. Not sure what to google for, neither.

3 Answers3

0

The forEach method belongs to the Array prototype (see here), therefore it can only be used on variables which are of type Array.

The QueryList type implements the Iterable interface (as per Angular docs here), therefore it allows looping with for ... of.

What the Google Chrome (or any other browser) console prints is different from what the object actually is.

Mantas
  • 89
  • 6
0

forEach is a method of an Array. TypeScript will only allow you to call methods it understands is available for that type.

If the type QueryList<> is not an array but rather an object that has the same behavior as an array at runtime TS will not know it.

You can either use the for..of loop or if you want to stick with forEach you can make QueryList<> extends Array<T>.

thitemple
  • 5,833
  • 4
  • 42
  • 67
0

you have to wait until markers are rendered 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");
    });
}
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37