Home  >  Q&A  >  body text

Can I use @ViewChild to set focus on a specific text area?

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();
  }

}

P粉477369269P粉477369269406 days ago490

reply all(2)I'll reply

  • P粉144705065

    P粉1447050652023-09-09 13:28:26

    The first thing is to pass the 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 directive like *ngIf/*ngFor then you can also pass {static: true, read: ElementRef} which will make elementRef available in ngOnInit , otherwise you must use AfterViewInit

    reply
    0
  • P粉436688931

    P粉4366889312023-09-09 11:08:33

    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:

    ngAfterViewInit(): void {
        // nativeElement is null
        console.log('test1',this.textarea?.nativeElement);
        setTimeout(() => {
                // nativeElement is not null
                console.log('test2',this.textarea?.nativeElement);
                this.textarea?.nativeElement.focus();
    }, 1000);

    }

    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

    reply
    0
  • Cancelreply