简体   繁体   中英

how to set focus for AutoComplete component from PrimeNG library in Angular

I am trying to use a AutoCompete component inside a Dialog element. I want the focus goes to the AutoComplement element when the Diaglog opens.

I have not find a exact tutorial on this.

My effect is based on this stackoverflow link: How to use Angular4 to set focus by element id

And this Github issue: https://github.com/primefaces/primeng/issues/2029 Although I do not understand some part like the onAfterShow event, and some guy in that thread tried and does not work.

My code goes like this(simplified):

Component

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

TypeScript:

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

or like that:

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

When when the diaglog opens, the onAfterShow() function is executed without error. However, the focus is not set on the autocomplete element.

Any suggestions where I got it wrong? Thank you in advance.

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();
}

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM