[英]Angular 2+ how to get focus to modal inputs on opening the modal?
在我構建的自定義模態組件中,我希望在模態打開時聚焦模態中的輸入
我嘗試了兩種方法:
1)使用ViewChild
和ElementRef
,然后在模式打開時觸發焦點(方法);
2) 使用document.getElementByID('test').focus()
方法;
他們都沒有工作
我嘗試測試另一個文檔屬性並且它有效。
document.getElementByID('test').innerHtml = 'test'
但不是重點
模態的簡化 html:
<div [class.modal--open]="_open">
<input #codeInput type="text" id='test'>
</div?
TS:
@ViewChild('codeInput') codeInput: ElementRef
@Input() set open(value: boolean) {
this._open = value;
if (value) {
// here is where i need to get focus on the input
document.getElementByID('test').focus() // did not work
this.codeInput.nativeElement.focus() // did not work
}
}
您在模態類聲明中有錯誤,更正它,它將起作用
<div [ngClass]="['modal', style]" [class.modal--open]="_open">
^
<div [ngClass]="modal" [class.modal--open]="_open">
如果你想做一些動態聚焦,那么你可以使用 afterviewInit 生命周期鈎子,在 viewInit 之后你使用渲染器而不是本地方法設置焦點。
在你的組件中
AfterViewinit() {
this._renderer.setAttribute(elRef,'focus',true);
}
我發現了問題,焦點正在工作,它只需要一些時間來觸發,我用setTimeOut()
包裝了focus()
方法並且它起作用了
if (value) {
setTimeout(() => {
this.codeInput.nativeElement.focus()
}, 1000)
}
對於那些使用 - ng-Bootstrap
只有在調用模態方法open(...)
后,才能通過 id 獲取元素,並調用方法focus()
public createCustomModal(modalDivElement: any, autoFocusElement?: string)
{
let ngbModalRef = this.ngbModalService.open(modalDivElement);
if (autoFocusElement)
{
document.getElementById(autoFocusElement).focus();
}
return ngbModalRef;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.