访问NgFor循环中的元素

Mat*_*ino 1 angular2-template angular

我的模板包含一个动态列表:

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

我想在用户点击它时更改项目的CSS类.我已经尝试使用的特性MouseEvent,如targetcurrentTarget,但EventTarget不提供访问类列表.所以我尝试将列表元素作为视图子元素获取:

@ViewChildren("nameitem") private nameItems: QueryList<ElementRef>;
Run Code Online (Sandbox Code Playgroud)

这也不起作用.在事件处理程序中,本机元素是未定义的:

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

我得到的错误是:Cannot read property "nativeElement" of undefined.有什么想法吗?

谢谢

Mat*_*ino 5

QueryList的元件可以除非不使用数组方式访问toArray时使用.所以这段代码失败了:

console.log(this.nameItems[i].nativeElement.classList.length);
Run Code Online (Sandbox Code Playgroud)

这段代码有效:

console.log(this.nameItems.toArray()[i].nativeElement.classList.length);
Run Code Online (Sandbox Code Playgroud)

疯.如果有人知道更好的方法,请告诉我.