搜索

首页  >  问答  >  正文

如何防止在Angular中点击模态框外部时关闭模态框?

我已经阅读了几个关于此问题的问答,所有的建议都是一个非常简单的解决方案:在负责打开模态框的按钮的HTML标签中添加

data-backdrop="static" data-keyboard="false"

对于我来说,这个按钮是:

<button type="button" class="btn btn-primary btn-danger m-2" data-bs-toggle="modal" data-bs-target="#exampleModal" data-backdrop="static" data-keyboard="false" (click)="onDelete(object.id)"><fa-icon [icon]="faTrash"></fa-icon></button>

完整的模态框是:

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <!-- <h5 class="modal-title text-center" id="exampleModalLabel">Biztosan törölni akarod?</h5> -->
        <button type="button" #closeButton class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <h5 class="modal-title text-center" id="exampleModalLabel">Biztosan törölni akarod?</h5>
        <p class="text-center">A törlés megerősítésével az adatbázisból is eltávolításra kerül a rekord.</p>
      </div>
      <div class="modal-footer justify-content-center">
        <button type="button" class="btn btn-danger" data-bs-dismiss="modal" (click)="confirmDelete()">Törlés</button>
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal" (click)="declineDelete()">Visszavonás</button>
      </div>
    </div>
  </div>
</div>

但是每次我按ESC键或者点击模态框外部,它都会关闭。我还尝试从TS中管理它,使用@ViewChild modal(引用模态框的DOM div),以及一个dialog: MatDialog属性,然后在按下Delete按钮时调用的onDelete()方法中,我只是简单地输入了this.modal.open(dialog, { disableClose: true });,但也没有起作用。我更倾向于只从HTML中解决它。我有什么遗漏吗?(我使用的是angular 14.1.1和bootstrap v5)

P粉805107717P粉805107717468 天前756

全部回复(1)我来回复

  • P粉398117857

    P粉3981178572023-09-14 18:12:13

    Backdrop必须设置为static,这样当点击它外部时模态框不会关闭,但是它被设置为data-bs-backdrop="static"而不是data-backdrop="static"

    <!-- 触发模态框的按钮 -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
      启动静态背景模态框
    </button>
    
    <!-- 模态框 -->
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="staticBackdropLabel">模态框标题</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button type="button" class="btn btn-primary">了解</button>
          </div>
        </div>
      </div>
    </div>

    回复
    0
  • 取消回复