1

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.

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

2

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.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • It works, so green check right away. I'd also like to know if there's a better approach to the whole concept, elimination a potential flaw in my design. The reason for me wondering is that it seems that the change detection needs a kick-start (according to your suggestion) and usually, such stuff "just work" when the rest of the software is set up properly. Or is it just one of those occasions? – Konrad Viltersten Apr 06 '19 at 22:30
  • I don't think that there is a better way because focus cannot be set through data binding. The only alternative that I know would be to set focus asynchronously (e.g. with `setTimeout`). – ConnorsFan Apr 06 '19 at 22:34
  • Thanks for the latest reply. It's both accepted and +1'ed, as it should be. I wonder if you'd have time to take a looks at a [similar question](https://stackoverflow.com/questions/55716795/focusing-input-box-programatically-from-another-component) but regarding a case of a change in the property invoked from outside of the component. If not, I'm still grateful for this reply. – Konrad Viltersten Apr 16 '19 at 21:27