您可以通过ViewChild 简单地访问模板变量。
在您的组件中:
@ViewChild('inp') // use the name of your template variable
input: ElementRef;
现在您可以访问输入,但它在ngAfterView 生命周期挂钩及更高版本中可用(请参阅here)
更新:要将此元素设置为焦点,您可以执行以下操作:
this.input.nativeElement.focus()
更新 2:有多种方法可以做到这一点。一种方法是通过EventEmitter 或Subject 通知您的子组件以将焦点设置到您的输入字段。另一种方法是通过ViewChild 访问子组件并执行一个函数,将焦点设置到您的输入字段。
1.选项:
myform.component.ts
focus$: Subject<void> = new Subject();
...
buttonClickFunction() {
this.focus$.next();
}
myform.component.html
<form>
<app-mycomponent [focus$]="focus$"></app-mycomponent>
...other components in this form
</form>
app-mycomponent.component.ts
@ViewChild('inp') // use the name of your template variable
input: ElementRef;
@Input()
focus$: Subject<void>;
ngAfterViewInit() {
this.focus$.subscribe(() => {
this.setFocusToInput();
});
}
setFocusToInput() {
this.input.nativeElement.focus()
}
2。选项:
myform.component.ts
@ViewChild(AppMyComponent) // your component class name
appMyComponent: AppMyComponent
...
// In a function or somewhere else you can call the function to set the focus
buttonClickFunction() {
this.appMyComponent.setFocusToInput();
}
app-mycomponent.component.ts
@ViewChild('inp') // use the name of your template variable
input: ElementRef;
...
setFocusToInput() {
this.input.nativeElement.focus()
}
目前,在你目前的情况下,我会向你推荐第二种选择。