Konrad Viltersten
Konrad Viltersten

Reputation: 39118

Can't set focus on an input box programmatically in Angular

I'm trying to follow a suggestion and have set a marker on the input control in my component like this.

<span (click)="onEditClick()"
      [class.hidden]="editing">{{value}}</span>
<input #input
      value="{{value}}"
      [class.hidden]="!editing">

I noticed that clicking the span hides it and presents the input but an additional click is required to make the input control actually focused for editing. I tried to focusify it as follows.

@ViewChild("input") input: ElementRef;

onEditClick() {
  this.editing = true;
  this.input.nativeElement.focus();
}

It doesn't work, so I verified that the native element is set and corresponds to what I expect. It did. And since there are no errors in the console, I'm a bit stuck not knowing how to diagnose it further.

I suspect that I'm missing something rather basic that can easily be inferred from the provided description.

Upvotes: 1

Views: 1101

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

The problem is that the input element is still hidden when you try to set focus on it. To make sure that the input element has become visible after setting the editing property, force change detection by calling ChangeDetectorRef.detectChanges():

onEditClick() {
  this.editing = true;
  this.changeDetectorRef.detectChanges();
  this.input.nativeElement.focus();
}

See this stackblitz for a demo.

Upvotes: 3

Related Questions