如何通过单击Angular上的按钮打开引导模态

时间:2020-08-25 11:53:44

标签: angular bootstrap-4

我有一个Bootstrap Modal以及下面的按钮。

      <!-- Button trigger modal -->
       <button type="button" class="btn btn-primary" data-toggle="modal" data- 
         target="#staticBackdrop">
         Launch static backdrop modal
       </button>

     <!-- Modal -->
     <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-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">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    ...
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Understood</button>
  </div>
</div>
</div>
</div>

当我单击按钮时,模态将打开,但是我想在屏幕加载后立即显示模态。

2 个答案:

答案 0 :(得分:0)

您是否在 angular.json 文件中添加了引导程序?像这样

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
        ]

答案 1 :(得分:0)

我建议您使用Angular兼容的引导程序,即ng-bootstrap,因为原始引导程序直接在DOM上运行,因此,如果您想干预Angular模板中的引导程序DOM操作,可能是有点难。

看看当您单击“按钮触发模式”时DOM内部发生了什么,那里有两个类。其中之一是“模态开放”注入人体,另一种是“显示”注入您的模态。您需要在Angular .ts文件中添加一些单击事件捕获器,这将负责将标志open设置为truefalse。然后,需要将该标志放入模态模板内的可选类中,如下所示:

<div class="modal fade" id="staticBackdrop" [class.show]="show" ...

但是您还应该记住,在关闭模式操作时,需要将此标志设置为false。然后,您只需要将此标志默认设置为true并在ngOnInit中将其设置为false。

相关问题