无法在Angular中以编程方式将焦点设置在输入框上

无法在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.

问题是,当您尝试将焦点设置在输入元素上时,该输入元素仍处于隐藏状态.为确保在设置 editing 属性后输入元素变得可见,请通过调用 ChangeDetectorRef.detectChanges():

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();
}

请参见此stackblitz 演示.