如何从 *ngFor 循环元素访问元素引用?

How can I access element reference from *ngFor loop element?

如何从 ngFor 循环访问元素引用? 我在这里做了一些样品。

在打字稿中

public onUpload(itemId: number):void {
   // how can I access element?
   this.listContainer.nativeElement.scrollTo(    ???     );
}

标记

<ul #list_container style="overflow-y:scroll;">
  <li *ngFor="var item of items">
    {{item.id}} - {{item.name}}
  </li>
</ul>

您可以通过

来使用它们
@ViewChild('list_container') list_container :ElementRef;

那么你就可以把它当作

 this.listContainer.nativeElement.scrollTo(..)

如果你想第n次访问child,你可以使用

@ViewChildren(ListItemDirective) list_container: QueryList<ListItemDirective>;

在这种情况下,您需要有一个指令用于迭代 children

@Directive({selector: 'list-item-directive'})
class ListItemDirective {
}

您需要将标记修改为

<li *ngFor="var item of items" list_container>

您可以使用 this.list_container.last

访问最后一个 child

使用查询选择器。

this.elementref.nativeElement.queryselector('ul li:nth-child(2)') 
{
    // do ur stuff here
}