ng-bootstra v4:将打开后的输入元素聚焦在模态内

时间:2017-09-21 10:20:01

标签: angular ng-bootstrap

我创建了一个带有NgbModal的模态组件,其中包含一些输入元素。当Modal打开时,应该打开第一个输入元素,但是我找不到方法,在模态打开后聚焦Input元素。

我可以得到输入元素(focus-on-newly-added-input-element),但是当我在调用`this.modalService.open(...)之后调用它时,它不会聚焦任何东西,因为元素没有' t还存在于DOM中。

所以我必须在渲染模态后调用它。

这是我到目前为止所做的:

open(content) {
    this.modalService.open(content, { size: 'lg' });
    // TODO
}

PS:我找到了angularjs和boostrap 3的答案:Call function after modal loads angularjs ui bootstrap

2 个答案:

答案 0 :(得分:0)

This Plunker演示了在打开模态时关注输入字段。

如果您根据"组件将模式设置为内容"示例(而不是"带有默认选项的模态"(https://ng-bootstrap.github.io/#/components/modal/examples)您可以在NgbdModalComponent的构造函数和{{open()中注入Renderer2(如果使用Angular 4) 1}}方法,使用以下代码进行聚焦:

let inputElement = this.renderer.selectRootElement('#focusMe');
inputElement.focus();

模态的相应HTML是:

<div class="modal-header">
  <h4 class="modal-title">Hi there!</h4>
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <p>Hello, {{name}}!</p>
  <input type="text" id="focusMe" />
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" (click)="activeModal.close('Close click')">Close</button>
</div>

答案 1 :(得分:0)

为模态体使用模板,并在要聚焦的元素上使用 ngbAutoFocus 指令

add-user-modal.component.html

<ng-template #content let-modal>
  <common-modal title="Invite your Teammates" [buttons]="buttons" [modal]="modal">
      <label for="emails">Enter your team members' email addresses to grant them access to your team's account. Enter one email address per line.</label>
      <textarea ngbAutoFocus id="emails" class="form-control" placeholder="Emails" [formControl]="emailsFormControl"></textarea>
  </common-modal>
</ng-template>

modal.component.html

<div class="modal-header">
  <div class="title-container">
    <h4 class="modal-title" id="modal-basic-title">{{ title }}</h4>
  </div>
  <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <ng-content></ng-content>
</div>
<div class="modal-footer">
  <ng-container *ngFor="let button of buttons">
    <button type="button" [class]="button.style" [disabled]="button.disabled"
      (click)="modal.close(button.resultIfClicked)">{{ button.text }}</button>
  </ng-container>
</div>