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

时间:2017-04-13 08:30:33

标签: angular ngfor

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

在TypeScript中

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>

2 个答案:

答案 0 :(得分:1)

您可以使用

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

然后您可以将其用作

 this.listContainer.nativeElement.scrollTo(..)

如果您想要访问第n个孩子,可以使用

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

在这种情况下,您需要为迭代的孩子提供指令

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

您需要将标记修改为

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

您可以使用this.list_container.last

访问最后一个孩子

答案 1 :(得分:1)

使用queryselector。

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