Here you may go for loop the <div class="post">
,
<div class="posts">
<div class="post">
<div>post content</div>
// Pass index here, if you want to achieve dynamically
<a class="comment" (click)="doSomething(0)">Comment</a>
<textarea [(ngModel)]= "model.text" class="comment-text" #txtArea name="text">
</textarea>
</div>
<div class="post">
<div>post content</div>
<a class="comment" (click)="doSomething(1)">Comment</a>
<textarea [(ngModel)]= "model.text" class="comment-text" #txtArea name="text">
</textarea>
</div>
</div>
Now in your ts file add the following imports,
import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';
Read elements using ViewChildren
and QueryList
like this,
@ViewChildren("txtArea") textAreas:QueryList<ElementRef>;
Finally your doSomething
event handler like this,
doSomething(index: number) {
this.textAreas.find((item, idx) => {
return idx === index;
}).nativeElement.focus();
}
Update
The above code will work with an array of posts
. So we don't need to hard-code the id like #txtArea1, #txtArea2 etc.
Please check here the DEMO_1
If you are iterating <div class="post">
like,
<div class="post" *ngFor="let post of posts; index as i">
You can pass the index
(here i
) to get corresponding TextArea
reference from QueryList
like below,
<a class="comment" (click)="textAreas.toArray()[i].nativeElement.focus()">Comment</a>
Check the complete code here DEMO_2