Reputation: 2681
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.
Upvotes: 6
Views: 10536
Reputation: 15442
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();
}
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
Upvotes: 12