在angular7中实现bootstrap模式对话框

问题描述 投票:0回答:1

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

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

angular bootstrap-4 bootstrap-modal
1个回答
0
投票

在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();
      }
    }

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

© www.soinside.com 2019 - 2024. All rights reserved.