使用renderer2设置输入框焦点

3

我有一个像下面这样的按钮,当我按下“空格键”时会打开一个模态框

<button type="button" (keydown.space)="openLg()" class="btn btn-link"></button>

我想要设置焦点在下面的输入框中:

<input class="form-control" type="text" id="amount" name="amount" [(ngModel)]="totalAmt_modal">

openLg函数是:

openLg() { 
    
 this.renderer.selectRootElement('#amount').focus();

}

我也导入了 renderer2

import { Component, OnInit, Renderer2} from '@angular/core';

constructor(private renderer: Renderer2){}

但是当我按下空格键时,它会显示以下错误。
core.js:4352 ERROR Error: The selector "#amount" did not match any elements
    at EmulatedEncapsulationDomRenderer2.selectRootElement (platform-browser.js:679)
    at BaseAnimationRenderer.selectRootElement (animations.js:267)
    at VoucherentryComponent.setfocus (voucherentry.component.ts:347)
    at VoucherentryComponent.openLg (voucherentry.component.ts:320)
    at VoucherentryComponent_tr_52_Template_button_keydown_space_2_listener (voucherentry.component.html:75)
    at executeListenerWithErrorHandling (core.js:15214)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:15249)
    at platform-browser.js:582
    at platform-browser.js:1281
    at ZoneDelegate.invoke (zone-evergreen.js:364)

有什么解决方案?我做错了什么?


我在这里尝试重现您的问题:https://stackblitz.com/edit/angular-ivy-hawgm4?file=src/app/app.component.ts。对我来说它运行良好。您能否在stackblitz.com上分享一个最小可重现的代码? - smtaha512
抱歉回复晚了,@smtaha512。问题出在模态框上。由于某种原因,它没有聚焦到模态框输入框上。我使用了ngbAutofocus。谢谢。 - Shuvo Barua
1个回答

0
问题出在模态框上。由于某种原因,它没有聚焦在模态框输入上。我使用了ngbAutofocus。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接