如何从 Angular 的 PrimeNG 库中为 AutoComplete 组件设置焦点

Hai*_*jin 6 html typescript primeng angular

我正在尝试在 Dialog 元素中使用 AutoCompete 组件。当 Diaglog 打开时,我希望焦点转到 AutoComplement 元素。

我还没有找到这方面的确切教程。

我的效果是基于这个stackoverflow链接: How to use Angular4 to set focus by element id

这个 Github 问题:https : //github.com/primefaces/primeng/issues/2029 虽然我不明白像 onAfterShow 事件这样的部分,但该线程中的一些人尝试过但不起作用。

我的代码是这样的(简化):

成分

<p-dialog [(visible)]="this.display" modal="true"(onShow)="this.onAfterShow($event)">
  <p-autoComplete  #autoCompleteObject>
  </p-autoComplete>
  <some-other-components>
<p-dialog>
Run Code Online (Sandbox Code Playgroud)

打字稿:

  @ViewChild('autoCompleteObject') private autoCompleteObject: AutoComplete ;
  onAfterShow(event){   this.autoCompleteObject.domHandler.findSingle(this.autoCompleteObject.el.nativeElement, 'input').focus();
  }
Run Code Online (Sandbox Code Playgroud)

或者像这样:

@ViewChild('autoCompleteObject', {read: ElementRef}) private autoCompleteObject: ElementRef ;
  onAfterShow(event){
    console.log("diaglog shows");
    this.autoCompleteObject.nativeElement.focus();
  }
Run Code Online (Sandbox Code Playgroud)

当diaglog 打开时, onAfterShow() 函数执行没有错误。但是,焦点未设置在自动完成元素上。

我哪里出错了有什么建议吗?先感谢您。

And*_*riy 11

Each autocomplete instance has a public function focusInput(). Once you have a reference to your instance via @ViewChild('autoCompleteObject')..., you can call focusInput() on this reference:

onAfterShow(event) {
  this.autoCompleteObject.focusInput();
}
Run Code Online (Sandbox Code Playgroud)

STACKBLITZ

UPDATE

This is related to primeng v1.0.xxx: In order to manually control focus within dialog add [focusOnShow]="false":

<p-dialog header="Title" 
          [focusOnShow]="false" 
          [(visible)]="display" 
          modal="true" 
          (onShow)="onAfterShow()">
   ...
</p-dialog>
Run Code Online (Sandbox Code Playgroud)

this way, the button does not "steal" the focus, STACKBLITZ updated