2017-04-13 179 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 
}