0

How can I access element reference from ngFor loop? I made some sample here.

In TypeScript

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

Markup

<ul #list_container style="overflow-y:scroll;">
  <li *ngFor="var item of items">
    {{item.id}} - {{item.name}}
  </li>
</ul>
1
  • what you trying to achieve ? please bit more explanation Commented Apr 13, 2017 at 8:43

2 Answers 2

1

You can use them either by using

@ViewChild('list_container') list_container :ElementRef;

then you can use it as

 this.listContainer.nativeElement.scrollTo(..)

If you want tp access nth child, you can use

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

In this case you need to have a directive for the iterated children

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

You need to modify your markup as

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

You can access the last child by using this.list_container.last

Sign up to request clarification or add additional context in comments.

1 Comment

I need access to n-th child. this way is just access to list container though. :(
1

Use queryselector.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.