我有一个前端角度应用程序,我希望将焦点设置到特定的文本区域,光标闪烁并准备好让用户在加载时在文本区域中键入。
在进行了一些谷歌搜索后,我认为 @ViewChild 可能是正确的选择。但到目前为止我已经能够让它工作了。
这是我的整个独立 ts 文件:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
Hello from {{name}}!
`
})
export class App {
@ViewChild('reference') textarea: ElementRef | undefined;
name = 'Angular';
ngAfterViewInit(): void {
this.textarea?.nativeElement.focus();
}
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
第一件事是将正确的选项传递给
@ViewChild:@ViewChild('myinput', {read: ElementRef})否则你将得到组件实例而不是 dom 节点。
如果你没有任何像*ngIf/*ngFor这样的结构指令,那么你也可以传递
{static: true, read: ElementRef},它将使elementRef在ngOnInit中可用,否则你必须使用AfterViewInit