[英]Renderer2 error - id did not match any elements
所以我有一个输入字段,我想专注于 Angular 应用程序中的负载。 我读到 Renderer2 方式是这样做的好方法,如果我在点击时调用 function 则它会起作用,例如:
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 演示
@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 />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.