[英]How can I access element reference from *ngFor loop element?
如何從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>
您可以通過以下方式使用它們
@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
訪問最后一個孩子
使用queryselector。
this.elementref.nativeElement.queryselector('ul li:nth-child(2)')
{
// do ur stuff here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.