【问题标题】:Implementing bootstrap modal dialog in angular7在 angular7 中实现引导模式对话框
【发布时间】:2019-08-20 13:11:59
【问题描述】:

我在实现一个简单的引导模式对话框时遇到了一段时间,并在大约 10 个不同的页面中找到了答案。考虑到我无法快速或清楚地找到答案,我想我会分享我的解决方案来帮助他人。 (下面第一个答案)

如果您必须添加多种类型的引导小部件,我建议您查看 (https://ng-bootstrap.github.io/#/home)

【问题讨论】:

标签: angular bootstrap-4 bootstrap-modal


【解决方案1】:

src/index.html中我将body标签的内容改为:

 <body>
    <app-root></app-root>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> 
    </script>
</body>

在调用模态的组件中,我在模板中:

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" (click)="showModal()">
  Open modal
</button>
<app-modal></app-modal>

在打字稿组件中

    showModal(): void {   
        this.displayService.setShowModal(true); 
        // communication to show the modal, I use a behaviour subject from a service layer here
    }

我在我拥有的模板中为模态构建了一个单独的组件

<!-- The Modal -->
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Modal Heading</h4>
        <button type="button" class="close" (click)="hideModal()">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        Modal body..
      </div>

      <!-- Modal footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" (click)="sendModal()" >Send</button>
        <button type="button" class="btn btn-danger" (click)="hideModal()">Close</button>

        <!-- this button is hidden, used to close from typescript -->
        <button type="button" id="close-modal" data-dismiss="modal" style="display: none">Close</button>
      </div>
    </div>
  </div>
</div>

在我的 Typescript 组件中

    import { Component, OnInit } from '@angular/core';

    // This lets me use jquery
    declare var $: any;

    @Component({
      selector: 'app-modal',
      templateUrl: './modal.component.html',
      styleUrls: ['./modal.component.css']
    })
    export class ModalComponent implements OnInit {
      constructor() { }

      ngOnInit() {
      }
      showModal():void {
        $("#myModal").modal('show');
      }
      sendModal(): void {
        //do something here
        this.hideModal();
      }
      hideModal():void {
        document.getElementById('close-modal').click();
      }
    }

现在模态对话框可以工作了,有一个发送功能,可以添加一些额外的逻辑,还有一个隐藏功能,可以从打字稿中关闭模态

【讨论】:

  • 为什么不用这个来关闭模态框呢? hideModal():void { $("#paymentModal").modal('hide'); }
  • 好问题,自从我检查这个已经有一段时间了,但据我所知,只是做隐藏不会触发 data-dismiss="modal",这意味着你的模态预先填充了重新打开它时的以前的数据。我知道我按照您建议的方式尝试过,但有理由改用我现在的方式。可能只有当你有某种形式时才需要它......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 2013-05-05
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2013-03-02
相关资源
最近更新 更多