繁体   English   中英

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

[英]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 />

你可以尝试:

ngOnInit() {
    setTimeout(() => this.renderer.selectRootElement('#myInput').focus());
}

有关本文的更多详细信息。

似乎在渲染之后有一个关于事件的长期讨论。 这个解决方案可能会有所帮助,或者(真的很难看)在我之前提出的解决方案中设置 100 毫秒的超时。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM