ngx bootstrap - 在模式打开时关注输入

ngx bootstrap - focus input on modal open

我有一个带有输入文本字段的模态框,当我打开模态框时,我想集中输入(这样用户就可以直接输入,而无需 select 输入框)。

我阅读了几种使用 ngx-bootstrap 执行此操作的不同方法。我已经尝试了很多,但其中 none 似乎有效。然而最接近的是这个。所以下面的代码突出显示了该字段,但没有 select 它。

模态输入字段:

<input autocomplete="off" list="autocompleteOff" type="text" class="text-input" id="childName" [(ngModel)]="childName" placeholder="Child's First Name" [autofocus]>

打开模型的代码(附加到按钮(单击)事件):

// Open Create Child Modal
openModal(template: TemplateRef<any>) {
    this.clearChildData();
    this.modalRef = this.modalService.show(template);
    this.modalService.onShown.pipe( tap(() => (document.querySelector('[autofocus]') as HTMLElement).focus()) ).subscribe();
}

我看过这个工作的演示,所以显然我遗漏了一些东西或者我错了,但不确定那是什么?

我会说这是一个时间问题。您需要先订阅onShown,然后才能调用modalService.show。您还应该将 take(1) 添加到 onShown 管道。否则每次使用模态服务显示模态时都会设置焦点,即使组件(和 [autofocus] 元素)已被销毁。