javascript - Renderer2 错误 - id 与任何元素都不匹配

标签 javascript angular typescript angular8 angular-renderer2

所以我有一个输入字段,我想专注于 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" />

知道这背后的原因是什么吗?

最佳答案

请尝试这个workig demo

 @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();
}

or

 ngAfterContentInit() {
this.renderer.selectRootElement(this.myInput.nativeElement).focus();
    }

in Html you have to do like

<input id="myInput" #myInput />

关于javascript - Renderer2 错误 - id 与任何元素都不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62298616/

相关文章:

javascript - 带有链 promise 的 NodeJS My SQL 查询

node.js - 如何使用带有 Node/Express 后端的 Angular 5 HttpClient get 方法下载 excel (xlsx) 文件?

javascript - 如何为我的案例制作最好的 firestore 模式?

typescript 默认导出未定义

node.js - Google App Engine 上的 NestJS 项目显示错误 "Could not write file"&& "EROFS: read-only file system"

javascript - 在 vue 1.x 中选择 `optgroup`

javascript - 如何在 AngularJS 中双重展开变量名

javascript JSON直接解析对象属性为int

html - Angular 9 - 具有相同名称的 formControlName 的不同 formGroupName 影响相同的 formControlName

css - matRipple 的背景颜色