[英]Unable to set focus on angular editor using document.getelementById(id)
I am using dyanamic id for angular-editor.我正在为角度编辑器使用动态 ID。 But I am unable to set the focus programatically.
但我无法以编程方式设置焦点。
I have tried the below code.我试过下面的代码。
document.getElementById(id).focus();
But always occurs this error但是总是出现这个错误
ERROR TypeError: Cannot read properties of null (reading 'focus')
Try this.尝试这个。
setTimeout(() => { document.getElementById(id).focus(); }, 500);
Please place it in AfterViewInit
请将其放在
AfterViewInit
中
Please use the @ ViewChild()
请使用
@ ViewChild()
You need to set a @ViewChild
to get access to the HTML element.您需要设置
@ViewChild
才能访问 HTML 元素。
<mat-form-field class="form-mat-field ml-5">
<mat-label class="filter-label">Name</mat-label>
<input matInput formControlName"name" type="text" #myElement/>
</mat-form-field>
In the HTML mark the element you want to access in the ts Component with for ex.在 HTML 中,在 ts 组件中使用 for ex 标记您要访问的元素。
#myElement
. #我的
#myElement
。
@ViewChild('myElement') firstItem: ElementRef;
....
ngAfterViewInit(): void {
this.firstItem.nativeElement.focus();
}
In the component you can then access that marked element with the @ViewChild
.在组件中,您可以使用
@ViewChild
访问该标记元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.