Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda