<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 } }Lo que quiero hacer es enfocarme en el área de texto recién agregada. Como podría hacerlo. Gracias
Cuando queremos establecer el foco en una entrada agregada, puede usar ViewChildren para obtener el "elementRef" y suscribirse a los cambios de 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 }) }En tu caso, como quieres enfocar el primero, puedes usar ViewChild (que solo obtiene el primero) y, después de agregar el FormControl, haz un setFocus -mira que el .html es igual-
@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(); })}
Puedes ver ambos métodos en este stackblitz