2017-04-13 176 views
0

我如何可以访问ngFor回路元件的参考? 我在这里做了一些示例。如何从* 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> 
+0

你想达到什么目的?请详细说明一下 –

回答

0

您可以通过使用

@ViewChild('list_container') list_container :ElementRef; 

然后使用他们,你可以使用它作为

this.listContainer.nativeElement.scrollTo(..) 

如果你想TP访问第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

+0

我需要访问n个孩子。 这种方式只是获得虽然列出容器。 :( –

0

使用queryselector。

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