使用Angular的ElementRef设置离子文本区域的焦点:“类型'ElementRef'不存在属性'setFocus'。”

gfe*_*els 3 typescript ionic-framework ionic3 angular

我创建了一个textarea组件,该组件在ngAfterViewInit()方法中创建时会自动聚焦:

ngAfterViewInit() {
    if(this.text.length===0){
    this.theinput.setFocus();
    }
  }
Run Code Online (Sandbox Code Playgroud)

它工作正常,行为完全符合我的预期。

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

@ViewChild('name') theinput: ElementRef;


<ion-textarea #name rows="1" ></ion-textarea>
Run Code Online (Sandbox Code Playgroud)

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

"Property 'setFocus' does not exist on type 'ElementRef'."
Run Code Online (Sandbox Code Playgroud)

在this.theinput.setFocus()代码行中。

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

对于这样的问题,是否有更好的解决方法?扩展ElementRef还是类似的东西?

Che*_*pan 6

尝试这个

使用ViewChild装饰器获取dom元素

@ViewChild('ref') ref:TextInput;
Run Code Online (Sandbox Code Playgroud)

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

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

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