skip to Main Content

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


  1. You want to use the ngAfterViewInit lifecycle hook

    https://angular.io/guide/lifecycle-hooks

    Respond after Angular initializes the component’s views and child views, or the view that contains the directive.
    See details and example in Responding to view changes in this document.

    Stackblitz: https://stackblitz.com/edit/stackblitz-starters-8evga1?file=src%2Fmain.ts

    Login or Signup to reply.
  2. The first thing is to pass correct options to @ViewChild:

    @ViewChild('myinput', {read: ElementRef})
    

    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 in ngOnInit, otherwise you have to use AfterViewInit

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search