'Focus on textarea in popup

When I click on a button , a popup will appear which consists of textarea. I want the textarea to be focused when the popup is opened.

I tried using autofocus, textarea.focus .. but it is not working.

Can anyone please help...

by default popup= false

<div *ngIf = "popup" class="post">
    <p>enter your answer</p>
    <textarea  #textarea1 id = "ta"></textarea>
</div>

<button (click)="popup= true; 
textarea1.focus()">Answer Popup</button>


Solution 1:[1]

The following works for me, however most likely there is a better way to do it in Angular using states and event binding instead of this more like "plain JavaScript" solution:

app.component.ts

import { Component, ElementRef } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
  constructor(private _elementRef: ElementRef) {
  }

  openPopUp() {
    const div = this._elementRef.nativeElement.querySelector('#the_div')
    div.style.display = 'block'
    const textarea = this._elementRef.nativeElement.querySelector('#the_textarea')
    textarea.focus()
  }
}

app.component.html

<div hidden id="the_div">
  <textarea id="the_textarea"></textarea>
</div>

<button (click)="openPopUp()">
  Answer Popup
</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Wolf