Smithy
Smithy

Reputation: 847

Renderer2 error - id did not match any elements

So I have an input field which I would like to focus on load in an Angular application. I read that the Renderer2 way is the good method of doing so, and it works if I call the function for example on click like so:

focusMyInput() {
    this.renderer.selectRootElement('#myInput').focus();
}

But if I try to make it focus on load, like this:

ngAfterViewInit() {
    this.renderer.selectRootElement('#myInput').focus();
}

It throws an error:

 The selector "#myInput" did not match any elements
    at DefaultDomRenderer2.selectRootElement

HTML:

<input id="myInput" />

Any idea what could be the reason behind this?

Upvotes: 2

Views: 2433

Answers (2)

Jadli
Jadli

Reputation: 860

Please try this 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 />

Upvotes: 3

Daniele Ricci
Daniele Ricci

Reputation: 15817

You could try with:

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

More details on this article.

It seems there is a long long discussion about having an event after the render. This solution could be helpful or (really ugly) set a 100ms timeout in my previous proposed solution.

Hope this helps.

Upvotes: 3

Related Questions