无法让Bootstrap 4.0 modal在角4项目中工作。
模态在一个简单的静态HTML页面中工作得很好:https://jsfiddle.net/Lq73nfkx/1/
<!-- MODAL -->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</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">Save changes</button>
</div>
</div>
</div>
</div>
您可以在下面的屏幕捕获中看到,按下显示模式会导致HTML在多个地方发生变化,不仅在模型HTML本身中,而且对文档的
<body>
元素也进行了操作。执行HTML操作的Bootstrap JavaScript似乎不会在角度4的项目中运行,当我在项目中使用完全相同的代码时,HTML根本没有改变。
有没有其他的方法我应该使用角4引导?或者我应该使用另一个角度为4的模态解,这不是自举的?
最佳答案
您可以使用ngx-bootstrap库来执行此操作。安装库后,请执行以下步骤。
步骤1:将以下代码添加到app.module.ts文件中。
import { ModalModule, BsModalRef } from 'ngx-bootstrap';
@NgModule({
imports: [ModalModule.forRoot(),...],
providers: [BsModalRef]
})
步骤2:复制以下代码并粘贴到app.commponent.html。
<button type="button" class="btn btn-primary" (click)="openModal(template)">Create template modal</button>
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
This is a modal.
</div>
</ng-template>
步骤3:最后将以下代码复制到app.component.ts。
import { Component, TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
export class AppComponent {
modalRef: BsModalRef;
constructor(private modalService: BsModalService) {}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template,{ backdrop: 'static', keyboard: false });
}
}