javascript - Renderer2 错误 - id 不匹配任何元素
问题描述
所以我有一个输入字段,我想专注于 Angular 应用程序中的负载。我读到 Renderer2 方式是这样做的好方法,如果我在单击时调用该函数,例如,它可以工作,如下所示:
focusMyInput() {
this.renderer.selectRootElement('#myInput').focus();
}
但是如果我试图让它专注于负载,就像这样:
ngAfterViewInit() {
this.renderer.selectRootElement('#myInput').focus();
}
它抛出一个错误:
The selector "#myInput" did not match any elements
at DefaultDomRenderer2.selectRootElement
HTML:
<input id="myInput" />
知道这背后的原因是什么吗?
解决方案
请试试这个工作演示
@ViewChild('myInput') myInput: ElementRef;//if it is direct child or element
@ContentChild('myInput') myInput: ElementRef;// if it is inside ng-content html
ngAfterViewInit() {
this.renderer.selectRootElement(this.myInput.nativeElement).focus();
}
或者
ngAfterContentInit() {
this.renderer.selectRootElement(this.myInput.nativeElement).focus();
}
在HTML中你必须这样做
<input id="myInput" #myInput />
推荐阅读
- javascript - 如何从 .then 的 promise 方法返回一个值?
- javascript - 如何在媒体查询下使用 Bootstrap 间隔变量?
- javascript - 如何更改组件中的路由确实已安装
- amazon-redshift - 错误消息是 [Amazon](500310) Invalid operation: This type of associated subquery pattern is not supported due to internal error
- api - 如何获取在 BotFather 注册的所有机器人的列表?
- python - 有没有办法使用 pyodbc 使用 executemany 进行批量更新
- arrays - 如何在 MongoDB 中删除数组中的单词
- data-structures - 在查找具有公共前缀的单词时,哪种数据结构将具有最佳的预期渐近性能?
- c++ - 比较向量中的元素时所花费的时间呈指数增长
- angular - 在Angular中定义值时如何仅在HTML元素中显示id属性