0

On the ngAfterViewInit lifecycle in angular, I'd like to focus() and select() the input. I've played around with it a bit and it seems like select() only works after I set a timeout. For example, the code below works as intended (input is focused and selected).

<input #el>

@ViewChild('el') el;

  ngAfterViewInit() {
    setTimeout(() => {
      this.el.nativeElement.focus();
      this.el.nativeElement.select();
    }, 0);
  }

But just doing this, only focus works.

  ngAfterViewInit() {
    this.el.nativeElement.focus();
    this.el.nativeElement.select();
  }

Can someone explain why this is?

cup_of
  • 6,397
  • 9
  • 47
  • 94
  • 2
    I suppose you are using Firefox? I had the same problem and it depends on the browser used. In Chrome it works without timeout, but in other browsers such as Firefox (and I think Edge), it doesn't. I don't have an explanation though. – Korfoo Mar 04 '19 at 09:13
  • check this answer on the same problem: https://stackoverflow.com/a/49520856/606104 – jahller Mar 04 '19 at 10:08

0 Answers0