如何使用代码在Angular 2中打开模态? [英] How to use code to open a modal in Angular 2?

查看:58
本文介绍了如何使用代码在Angular 2中打开模态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我们在<button>中使用data-target="#myModal"来打开模态.现在,我需要使用代码来控制何时打开模态.

Usually we use data-target="#myModal" in the <button> to open a modal. Right now I need use codes to control when to open the modal.

如果使用[hidden]*ngIf进行显示,则需要删除class="modal fade",否则,模态将永远不会显示.像这样:

If I use [hidden] or *ngIf to show it, I need remove class="modal fade", otherwise, the modal will never show. Like this:

<div [hidden]="hideModal" id="myModal">

但是,在这种情况下,删除class="modal fade"后,模态将不会淡入,并且背景中没有阴影.更糟糕的是,它将显示在屏幕底部而不是屏幕中心.

However, in this case, after removing class="modal fade", the modal won't fade in and has no shade in the background. And what's worse, it will show at the screen bottom instead of screen center.

是否可以保留class="modal fade"并使用代码将其打开?

Is there a way to keep class="modal fade" and use code to open it?

<button type="button" data-toggle="modal" data-target="#myModal">Open Modal</button>

<div id="myModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
    </div>
  </div>
</div>

推荐答案

这是我发现的一种方法.您可以添加一个隐藏按钮:

This is one way I found. You can add a hidden button:

<button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>

然后使用代码单击"按钮以打开模式:

Then use the code to "click" the button to open the modal:

document.getElementById("openModalButton").click();

这种方式可以保持模态的引导样式和动画中的淡入淡出.

This way can keep the bootstrap style of the modal and the fade in animation.

这篇关于如何使用代码在Angular 2中打开模态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆