代码之家  ›  专栏  ›  技术社区  ›  Konrad Viltersten

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

  •  1
  • Konrad Viltersten  · 技术社区  · 6 年前

    我试着跟着你 a suggestion

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

    @ViewChild("input") input: ElementRef;
    
    onEditClick() {
      this.editing = true;
      this.input.nativeElement.focus();
    }
    

    它不起作用,所以我验证了native元素是否已设置,并与我期望的内容相对应。是的。由于控制台中没有错误,我有点困在不知道如何进一步诊断它。

    我怀疑我遗漏了一些基本的东西,可以很容易地从提供的描述中推断出来。

    1 回复  |  直到 6 年前
        1
  •  2
  •   ConnorsFan    6 年前

    问题是,当您试图对输入元素设置焦点时,它仍然是隐藏的。确保在设置 editing 属性,通过调用 ChangeDetectorRef.detectChanges() :

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

    看到了吗 this stackblitz 演示一下。