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

Renderer2 error - id did not match any elements

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

你可以试试:

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

有关 this article 的更多详细信息。

关于渲染后的事件似乎已经进行了很长时间的讨论。 This solution 在我之前提出的解决方案中可能会有所帮助或(真的很难看)设置 100 毫秒超时。

希望对您有所帮助。