6

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.

Haijin
  • 2,561
  • 2
  • 17
  • 30

1 Answers1

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

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

Andriy
  • 14,781
  • 4
  • 46
  • 50
  • I believe it's a valid solution, but for some unknown reason it still does not work for me. – Haijin Oct 02 '18 at 15:27
  • please update my or create a new stackblitz with non-working version and I will try to help – Andriy Oct 02 '18 at 19:51
  • https://stackblitz.com/edit/angular-mmce7e?file=src/app/app.component.html. Adding a button, the focus is no longer on the p-autocomplete component. – Haijin Oct 02 '18 at 20:16
  • it is weird, button "steals" a focus from the input, as a workaround you can add `focus` to your button like ``. I do not like this workaround, but it is the only one I thought of. Please note that this will cancel tab selection (pressing TAB to select button while input is focused). I updated my stackblitz – Andriy Oct 02 '18 at 21:23