MatthewScarpino
MatthewScarpino

Reputation: 5936

Accessing elements in an NgFor loop

My template contains a dynamic list:

<ol>
  <li #nameitem *ngFor="let name of names; let i = index" class="classA"     
      (click)="handleClick(i)">{{ name }}</li>
</ol>

I want to change an item's CSS class when the user clicks on it. I've tried using properties of the MouseEvent such as target and currentTarget, but the EventTarget doesn't provide access to the class list. So I tried obtaining the list elements as view children:

@ViewChildren("nameitem") private nameItems: QueryList<ElementRef>;

This isn't working either. In the event handler, the native element is undefined:

private handleClick(i: number) {
  console.log(this.nameItems[i].nativeElement.classList.length);
}

The error I get is: Cannot read property "nativeElement" of undefined. Any thoughts?

Thanks

Upvotes: 2

Views: 2520

Answers (1)

MatthewScarpino
MatthewScarpino

Reputation: 5936

A QueryList's elements can't be accessed with array notation unless toArray is used. So this code fails:

console.log(this.nameItems[i].nativeElement.classList.length);

And this code works:

console.log(this.nameItems.toArray()[i].nativeElement.classList.length);

Crazy. If anyone knows a better way, please let me know.

Upvotes: 8

Related Questions