在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()">×</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();
}
}
现在模态对话框可以工作了,有一个发送功能,可以添加一些额外的逻辑,还有一个隐藏功能,可以从打字稿中关闭模态