Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to set focus on a dynamically added text area (angular material)
<button (click)="addTextArea()">Add Comment</button>

<div formArrayName="comments">
  <div *ngFor="let comment of commentsArray.controls; let i=index>
    <textarea>{{comment.value..}}</textarea>
  </div>
</div>
addTextArea() {
 const fc1 = this.fb.control('', [Validators.required]);
 const fc2 = this.fb.control('', [Validators.required]);

 this.commentsArray.insert(0,
   this.fb.group({
      code: fc1,
      value:fc2
   }


}

What I want to do is set focus on the newly added textarea. How would I do that. Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When we want to set focus to an input added you can use ViewChildren to get the "elementRef" and subscribe to changes of the QueryList

  <div formArrayName="comments">
    <div *ngFor="let comment of commentsArray.controls; let i = index"
      [formGroupName]="i">
      <mat-form-field class="example-full-width" appearance="fill">
        <!--see the template reference variable "commentInput"
        <textarea matInput #commentInput formControlName="value"></textarea>
      </mat-form-field>
    </div>
  </div>


@ViewChildren('commentInput,{read:ElementRef}) comments:QueryList<ElementRef>

ngAfterViewInit()
{
   this.comments.changes.subscribe(_=>{
        this.comments.first.nativeElement.focus() //<--if you want to 
                                                  // focus the first
        this.comments.last.nativeElement.focus() //<--if you want to 
                                                  // focus the last
   })
}

In your case, as you want focus the first you can use ViewChild (that only get the first) and, after added the FormControl, make a setFocus -see that the .html is equal-

@ViewChildren('commentInput',{read:ElementRef}) firstComment:ElementRef

//in your function addTextArea
addTextArea() {
 ....
 this.commentsArray.insert(0,...);

 //you need enclosed in a setTimeout to give time to Angular to draw the
 //element
 setTimeout(()=>{
   this.firstComment.nativeElement.focus();
 })

}

You can see both methods in this stackblitz

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!