Can I use @ViewChild to set focus on a specific text area?
P粉477369269
P粉477369269 2023-09-08 16:58:05
0
2
513

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粉477369269
P粉477369269

reply all(2)
P粉144705065

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

P粉436688931

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template