简体   繁体   English

无法使用 document.getelementById(id) 将焦点设置在 angular 编辑器上

[英]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.

相关问题 Angular document.getElementById 不能动态使用插值 - Angular document.getElementById not working with interpolation dynamically angular4 / typescript中的document.getElementById替换? - document.getElementById replacement in angular4 / typescript? 替换 Angular 中的 document.getElementById('checkBox') - Replacing document.getElementById('checkBox') in Angular 是否有 Angular 的做法: document.getElementById(id).style.display = &quot;none&quot;; - Is there an Angular way of doing: document.getElementById(id).style.display = "none"; 要在DOM中查找元素而不使用在angular 2+中使用* ngFor生成的document.getElementById() - To find the element in DOM without using document.getElementById() generated using *ngFor in angular 2+ Angular 测试 - 如何在 angular 测试中模拟 document.getElementbyId? - Angular test - how to mock document.getElementbyId in angular test? Angular 12 对象在 document.getElementById(elementId) 中可能为“null” - Angular 12 Object is possibly 'null' in document.getElementById(elementId) document.getelementbyid 始终在 angular 13 中返回 null - document.getelementbyid always returns null in angular 13 带有 Nrwl/Nx 的 Angular SSR - 外部库调用 document.getElementById - Angular SSR with Nrwl/Nx - external library calls document.getElementById AngularJS2:如何将注意力集中在document.getElementById(..)。焦点在javascript中? - AngularJS2: How to focus input like document.getElementById(..).focus in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM