首页 > 解决方案 > 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" />

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

标签: javascriptangulartypescriptangular8angular-renderer2

解决方案


请试试这个工作演示

 @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 />

推荐阅读