[英]Return focus to previous input after viewing modal
我正在開發一個 Angular 應用程序,其中有一個包含許多輸入的表單需要填寫。 在填寫表單時,用戶可以選擇打開一個模式,他們可以在其中使用熱鍵輸入注釋。 我想要做的是,一旦用戶關閉模態,將焦點返回到先前聚焦的輸入字段。
到目前為止,我似乎有一個可行的解決方案,但它似乎非常乏味,我不確定這是否是執行此類操作的最佳方法。
在每個input
字段上,我都有一個(focus)
將變量prevFocus
設置為輸入名稱。 例如:
<input
(focus)="prevFocus = 'customerName'"
name="customerName"
placeholder="Name"
type="text"
pInputText
formControlName="customerName"
/>
這個變量被存儲,當用戶關閉模態時,會調用一個函數:
closed() {
console.log(this.prevFocus);
setTimeout(() => {
this.setFocus(`${this.prevFocus}`);
});
}
setFocus(name) {
const ele = this.form.nativeElement[name];
if (ele) {
ele.focus();
}
}
setTimeout()
用於確保在加載組件后填充輸入。
我的問題是,我有超過 80 個輸入字段,對於每個輸入來說這似乎很乏味。 但是,這是最好的方法嗎? 有沒有人做過類似的事情,在做不同的動作或暫時失去焦點后焦點會返回?
這里是我創建的 Stackblitz 來展示我在看什么。 有一些功能,例如熱鍵快捷方式,我正在使用 PrimeNG 庫。 該庫和其他函數與返回到先前聚焦的輸入的特定關注無關,但它們被包含在內以獲得完整的用戶體驗:以輸入為焦點開始填寫表單 → 使用熱鍵 (alt + a) 打開modal → 單擊esc
或單擊 x 關閉 → 輸入焦點返回。
您可以使用document.activeElement
保存當前焦點元素並在關閉模態后調用activeElement.focus()
為可聚焦元素創建類型
export type FocusableElement = HTMLInputElement | HTMLSelectElement // add more if you wan
以及設置 activeElement 的代碼
activeElement:FocusableElement
constructor(
private eventManager: EventManager,
@Inject(DOCUMENT) private document: any
) {
this.addShortcut({ keys: 'alt.a' }).subscribe(() => {
this.activeElement = document.activeElement as FocusableElement;
this.showModalDialog();
});
}
closed() {
setTimeout(() => {
if(this.activeElement){
this.activeElement.focus()
}
});
}
如果(如 stackblitz 示例所示)所有控件或多或少都相同,但它們之間只有一些變化,您可以改為創建具有所需屬性的對象數組; 例如:
const formList= [
{ name: "customerAddress"
placeholder: "Address"
type: "text"
name: "customerAddress"
formControlName: "customerAddress"}
]
然后在 HTML 中循環遍歷它只設置一次:
<form #form>
<ng-container *ngFor="formItem of formList">
<input
(focus)="prevFocus = formItem.name"
[name]=formItem.name
[placeholder]=formItem.placeholder
[type]=formItem.placeholder
pInputText
[formControlName]=formItem.formControlName
/>
</ng-container>
</form>
如果您可能有除 input 之外的其他元素,您可以使用基於type
屬性的 Case 語句來根據type
創建不同的元素。 這也將允許您靈活地在數組中添加任何新字段並自動創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.