首页  >  问答  >  正文

可以使用@ViewChild将焦点设置在特定的文本区域吗?

我有一个前端角度应用程序,我希望将焦点设置到特定的文本区域,光标闪烁并准备好让用户在加载时在文本区域中键入。

在进行了一些谷歌搜索后,我认为 @ViewChild 可能是正确的选择。但到目前为止我已经能够让它工作了。

这是我的整个独立 ts 文件:

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 天前488

全部回复(2)我来回复

  • P粉144705065

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

    第一件事是将正确的选项传递给@ViewChild

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

    否则你将得到组件实例而不是 dom 节点。

    如果你没有任何像*ngIf/*ngFor这样的结构指令,那么你也可以传递 {static: true, read: ElementRef},它将使elementRef在ngOnInit中可用,否则你必须使用AfterViewInit

    回复
    0
  • P粉436688931

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

    我认为代码不起作用,因为 nativeElement 尚未在 DOM 中。 以下内容有效(您应该在控制台(test1)中看到 nativeElement 在 ngAfterViewInit 的开头为 null)。也许你必须增加 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);

    }

    此处描述了等待 nativeElement 出现在 DOM 中的更具确定性的方法(比 setTimeout):让函数等待元素存在

    回复
    0
  • 取消回复