将焦点状态设置为字段+角度4
问题描述:
我有焦点相关的问题。我需要的是在组件的onInit函数中的第一个字段上设置焦点状态。但我无法正确瞄准这个领域。将焦点状态设置为字段+角度4
我曾尝试
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">
thsi是在部件的formbuilder结构:
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: [''],
})
});
}
对不起朋友。我一遍又一遍地得到相同的错误。
错误类型错误:无法读取的不确定
答
财产 'nativeElement' 关注你的视场已被初始化后:
ngAfterViewInit(){
// Work around for "ExpressionChangedAfterItHasBeenCheckedError"
setTimeout(()=> { this.ePaciente.nativeElement.focus() }, 10);
}
这里是一个工作Plunker Demo
答
将它移动到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;
}
+0
这对你有帮助吗? – Vega
答
您应该使用其他r组件生命周期钩 - ngAfterViewInit
,因为它的视图及其子视图被初始化后立即被触发。
https://angular.io/guide/lifecycle-hooks
也是钩子回调使用的setTimeout内,以确保所述第一变化检测有机会运行和元素呈现(以便可聚焦的输入)。您不必指定延迟参数,因为您只想等待下一个打勾。
ngAfterViewInit() {
setTimeout(() => {
this.ePaciente.nativeElement.focus();
});
}
它的工作原理,但在控制台我得到了:错误TypeError:无法读取此字段未定义的属性'nativeElement'。多次!!! –
你怎么定义'ePaciente'?你能否更新我提供的plunker链接中的代码?我没有得到任何错误 – Faisal