首页 > 解决方案 > 使用 Angular 的 ElementRef 设置 ion-textarea 的焦点:“类型 'ElementRef' 上不存在属性 'setFocus'。”

问题描述

我创建了一个 textarea 组件,当它在 ngAfterViewInit() 方法中创建时它会聚焦于自身:

ngAfterViewInit() {
    if(this.text.length===0){
    this.theinput.setFocus();
    }
  }

它工作得很好,行为完全符合我的预期。

我正在使用 ElementRef 来获取 ion-textarea 组件:

@ViewChild('name') theinput: ElementRef;


<ion-textarea #name rows="1" ></ion-textarea>

但是,在运行ionic serve和构建应用程序时,它不会构建并显示错误:

"Property 'setFocus' does not exist on type 'ElementRef'."

this.theinput.setFocus()代码行。

如果我注释掉这行代码,构建应用程序,然后取消注释 - 一切都按预期工作。然而,这不是一个好的解决方案。

对于这样的问题有更好的解决方法吗?扩展 ElementRef 或类似的东西?

标签: angulartypescriptionic-frameworkionic3

解决方案


试试这个

使用 ViewChild 装饰器获取 dom 元素

@ViewChild('ref') ref:TextInput;

然后使用 nativeElement ,它是 dom 中的 textarea ,其中包括焦点方法。

ngAfterViewInit() {
    if(this.text.length===0){
    this.ref['_native'].nativeElement.focus();
    }
  }

示例:https:https: //stackblitz.com/edit/ionic-hatcjc


推荐阅读