How to make focus on input, which is hidden at first, but opens when clicked on a button? The autofocus attribute only works the first time, and the 'nativeElement' of undefined. On jQuery, everything is simple, but you need to do it without it.

<input type="text" *ngIf="isVisible" #test autofocus> <button (click)="testAction()">Test</button> @ViewChild('test') test: ElementRef; isVisible = false; testAction() { this.isVisible = !this.isVisible; this.test.nativeElement.focus(); } 

Other method:

 testAction() { this.isVisible = !this.isVisible; if (this.test && this.test.nativeElement) { setTimeout(() => this.test.nativeElement.focus(), 800); } } 

    1 answer 1

     <input type="text" *ngIf="isVisible" #test autofocus> <button (click)="testAction()">Test</button> @ViewChild('test') test: ElementRef; isVisible = false; testAction() { this.isVisible = !this.isVisible; const obs = Observable.timer(0).subscribe(()=>{ if(thi.test && this.test.nativeElement){ this.test.nativeElement.focus(); }); } 
    • Connected import {Observable} from 'rxjs / Observable'; and how to connect the timer? - Oleg Zinchenko
    • one
      import timer 'rxjs / add / observable / timer'; - Zohid
    • Thanks It works. If} handle was lost - Oleg Zinchenko