I have a front-end angular app in which I would like to have the focus set to a particular textarea with the cursor blinking and ready to have the user type in the text area upon loading.
After doing some Googling I thought that @ViewChild might be the way to go. But so far I have been able to get it to work.
This is my textarea in the html:
<textarea #myinput matInput placeholder="I want the cursor to be in this box and ready for the user to type text upon init.">
</textarea>
And this where I try to set the focus in my ts file:
//declare myInputField
@ViewChild("myinput") myInputField: ElementRef;
//and then initialize it in ngOnInit - and I do know that it's getting here
ngOnInit(): void {
this.myInputField.nativeElement.focus();
}
But alas when the form comes up there is no focus on the component.
Thanks much.
2
Answers
You want to use the
ngAfterViewInit
lifecycle hookhttps://angular.io/guide/lifecycle-hooks
Stackblitz: https://stackblitz.com/edit/stackblitz-starters-8evga1?file=src%2Fmain.ts
The first thing is to pass correct options to
@ViewChild
:otherwise you will get component instance instead of dom node.
If you don’t have any structural directives like *ngIf/*ngFor then you can also pass
{static: true, read: ElementRef}
, it will make elementRef available inngOnInit
, otherwise you have to useAfterViewInit