0

How do I focus on input, which is hidden first, but opens on the click of a button? The autofocus attribute only works the first time, and 'nativeElement' of undefined. On jQuery everything is simple, but I need to do 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();
}
Oleg Zinchenko
  • 503
  • 7
  • 16
  • 2
    Instead of `*ngIf` use `[hidden]`. Using `*ngIf` will prevent the DOM element from rendering which is why you can't focus it, since it doesn't exist. – Hoyen Mar 30 '18 at 16:36

2 Answers2

0

I did the something similar to what you're asking; however, I did it using a directive:

import { Directive, ElementRef, Input, OnChanges } from '@angular/core';

@Directive({
  selector: '[afnFocus]'
})
export class FocusDirective implements OnChanges {
  @Input() afnFocus: boolean;

  constructor(private el: ElementRef) { }

  ngOnChanges() {
    if (this.afnFocus) {
      this.el.nativeElement.focus();
    }
  }

}

Then place the directive on the element and tie it to the boolean isVisible.

Andrew Lobban
  • 2,065
  • 2
  • 24
  • 38
0

Another method

testAction() {
 this.isVisible = !this.isVisible;

 if (this.test && this.test.nativeElement) {
    setTimeout(() => this.test.nativeElement.focus(), 800);
 }
}
Oleg Zinchenko
  • 503
  • 7
  • 16