[英]how to set focus for AutoComplete component from PrimeNG library in Angular
I am trying to use a AutoCompete component inside a Dialog element.我正在尝试在 Dialog 元素中使用 AutoCompete 组件。 I want the focus goes to the AutoComplement element when the Diaglog opens.
当 Diaglog 打开时,我希望焦点转到 AutoComplement 元素。
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我的效果是基于这个stackoverflow链接: 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.这个 Github 问题: https : //github.com/primefaces/primeng/issues/2029虽然我不明白像 onAfterShow 事件这样的部分,但该线程中的一些人尝试过但不起作用。
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.当diaglog 打开时, onAfterShow() 函数执行没有错误。 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()
.每个
autocomplete
实例都有一个公共函数focusInput()
。 Once you have a reference to your instance via @ViewChild('autoCompleteObject')...
, you can call focusInput()
on this reference:一旦你通过
@ViewChild('autoCompleteObject')...
引用了你的实例,你可以在这个引用上调用focusInput()
:
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"
:这与primeng v1.0.xxx有关:为了在对话框中手动控制焦点添加
[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这样,按钮不会“窃取”焦点,STACKBLITZ 更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.