如何防止在Angular中點擊模態框外部時關閉模態框?
P粉805107717
P粉805107717 2023-09-13 20:32:07
0
1
723

我已經閱讀了幾個關於此問題的問答,所有的建議都是一個非常簡單的解決方案:在負責打開模態框的按鈕的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粉805107717
P粉805107717

全部回覆(1)
P粉398117857

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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板