簡體   English   中英

Angular 2+如何在打開模態時關注模態輸入?

[英]Angular 2+ how to get focus to modal inputs on opening the modal?

在我構建的自定義模態組件中,我希望在模態打開時聚焦模態中的輸入

我嘗試了兩種方法:

1)使用ViewChildElementRef ,然后在模式打開時觸發焦點(方法);

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
    }
  }

測試演示https://stackblitz.com/edit/angular-2ye3ag

只需在輸入字段中使用自動對焦

<input type="text" name="firstName" autofocus>

工作示例

您在模態類聲明中有錯誤,更正它,它將起作用

<div  [ngClass]="['modal', style]" [class.modal--open]="_open">
                    ^
<div  [ngClass]="modal" [class.modal--open]="_open">

https://stackblitz.com/edit/angular-zsszxc

如果你想做一些動態聚焦,那么你可以使用 afterviewInit 生命周期鈎子,在 viewInit 之后你使用渲染器而不是本地方法設置焦點。

在你的組件中

AfterViewinit() {    
this._renderer.setAttribute(elRef,'focus',true);    
}

我發現了問題,焦點正在工作,它只需要一些時間來觸發,我用setTimeOut()包裝了focus()方法並且它起作用了

    if (value) {
      setTimeout(() => {
        this.codeInput.nativeElement.focus()
      }, 1000)
    }

完整的解決方案https://stackblitz.com/edit/angular-2ye3ag

對於那些使用 - 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM