I have a front-end angular app and I want to set focus to a specific textarea and have the cursor flash and be ready for the user to type in the textarea when it loads.
After doing some googling, I think @ViewChild might be the right choice. But so far I've been able to get it working.
This is my entire standalone ts file:
import { Component, ElementRef, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello from {{name}}!</h1> <textarea #reference placeholder="Start typing"></textarea> ` }) export class App { @ViewChild('reference') textarea: ElementRef<HTMLTextAreaElement> | undefined; name = 'Angular'; ngAfterViewInit(): void { this.textarea?.nativeElement.focus(); } }
The first thing is to pass the correct options to
@ViewChild
:Otherwise you will get component instance instead of dom node.
If you don't have any structural directive like *ngIf/*ngFor then you can also pass
{static: true, read: ElementRef}
which will make elementRef available inngOnInit
, otherwise you must useAfterViewInit
I think the code doesn't work because the nativeElement isn't in the DOM yet. The following works (you should see in the console (test1) that nativeElement is null at the beginning of ngAfterViewInit). Maybe you have to add 1000ms:
}
A more deterministic way of waiting for a nativeElement to appear in the DOM is described here (than setTimeout): Have the function wait for the element to exist