angular - 使用 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 或类似的东西?
解决方案
试试这个
使用 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
推荐阅读
- python - 查看是否在 df2['Description'] 的任何位置找到 df1[Keyword'] 中的字符串列表,如果 df2 没有匹配则删除行
- json - 在 Swagger UI 中美化 Json 响应
- sql - 在 Oracle 数据库中更改用户配置文件
- python - 绘制每日级别数据,但仅使用月级别标签
- python - Selenium 在按钮单击后不显示表格内容
- excel - Excel 中的 TODAY 函数,自动更新
- sql - SQL转换:多行到一行
- c - SDL 2 C 编译器标志
- excel - 使用 textjoin 删除重复项并包含条件
- c - C程序在Linux命令行中导致分段错误,但在gdb中正常退出