将焦点状态设置为场+角度 4



我有一个与焦点相关的问题。 我需要的是在组件的 onInit 函数(第一个字段(中的字段上设置焦点状态。 但我无法正确瞄准该领域。

我试过了

export class EgrCrearRecetaComponent implements OnInit {
@ViewChild('paciente') ePaciente; 
...
}

并在 onInit 函数中

ngOnInit() {
this.buildForm();
// try to set
this.ePaciente.nativeElement.focus();
...
}

这是我忘了说的,我正在使用反应式形式,所以我不能使用 #paciente,我正在使用

<input type="text" pInputText formControlName="paciente" class="form-control" placeholder="Dni Paciente">

这是组件中的表单构建器结构:

buildForm(): void {
this.recetaform = this.fb.group({
paciente: ['', [<any>Validators.required, <any>Validators.minLength(7), <any>Validators.maxLength(9)]],
femision: [this.fechaHoy(), [<any>Validators.required]],
servicio: ['', [<any>Validators.required]],
idServicio: ['', [<any>Validators.required]],
turno: ['', [<any>Validators.required]],
prestador: ['', [<any>Validators.required]],
idPrestador: ['', [<any>Validators.required]],
diagnostico: ['', [<any>Validators.required]],
idDiagnostico: ['', [<any>Validators.required]],
productofgn: this.fb.group({
cb: [''],
producto: [''],
lote: [''],
cant: [''],
dias: [''],
})
});

}

对不起,朋友们。我一遍又一遍地收到同样的错误。

错误类型错误:无法读取未定义的属性"本机元素">

将其移至 AfterViewChecked((

...
import { AfterViewChecked} from '@angular/core';
..
export class EgrCrearRecetaComponent implements OnInit, AfterViewChecked {
....
toFocus=true;
ngAfterViewChecked() {
if (this.toFocus) {
this. ePaciente.nativeElement.focus();
}
this.toFocus = false;
}

您应该使用另一个组件生命周期挂钩 -ngAfterViewInit因为它在其视图和子视图初始化后立即触发。
https://angular.io/guide/lifecycle-hooks

同样在该钩子回调中使用 setTimeout 来确保第一个更改检测有机会运行并呈现元素(以便作为可聚焦的输入(。您不必指定延迟参数,因为您只想等待下一个即时报价。

ngAfterViewInit() {
setTimeout(() => {
this.ePaciente.nativeElement.focus();
});
}

在视图初始化后聚焦您的字段:

ngAfterViewInit(){
// Work around for "ExpressionChangedAfterItHasBeenCheckedError" 
setTimeout(()=> { this.ePaciente.nativeElement.focus() }, 10);
}

这是一个有效的 Plunker 演示

最新更新