SunilK
SunilK

Reputation: 157

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

Upvotes: 0

Views: 500

Answers (1)

Eliseo
Eliseo

Reputation: 57919

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

Upvotes: 1

Related Questions