gpt4 book ai didi

angular - 使用 Angular 的 ElementRef : "Property ' setFocus' does not exist on type 'ElementRef' . 设置 ionic 文本区域的焦点“

转载 作者:太空狗 更新时间:2023-10-29 18:14:54 25 4
gpt4 key购买 nike

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

最佳答案

试试这个

使用ViewChild装饰器获取dom元素

@ViewChild('ref') ref:TextInput;

然后使用 nativeElement,它是 dom 中的文本区域,其中包含 focus 方法。

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

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

关于angular - 使用 Angular 的 ElementRef : "Property ' setFocus' does not exist on type 'ElementRef' . 设置 ionic 文本区域的焦点“,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com