【问题标题】:Setting focus of ion-textarea with Angular's ElementRef: "Property 'setFocus' does not exist on type 'ElementRef'."使用 Angular 的 ElementRef 设置 ion-textarea 的焦点:“类型 'ElementRef' 上不存在属性 'setFocus'。”
【发布时间】:2019-01-23 17:30:33
【问题描述】:

我创建了一个 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 或类似的东西?

【问题讨论】:

    标签: angular typescript ionic-framework ionic3


    【解决方案1】:

    试试这个

    使用 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

    【讨论】:

    • 好的,这行得通。但是-您能否简要说明此解决方案?这算不算不好的做法?
    • 这不是一个坏习惯,因为我们使用 ViewChild Decorator 来触发 nativeElement 方法
    • this.ref._native.nativeElement.focus();
    猜你喜欢
    • 2017-10-06
    • 2020-11-13
    • 2021-06-21
    • 2018-04-11
    • 2018-09-28
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多