如何解决Bootstrap Modal 中的 Angular DataTable,dtElement 未定义
我正在尝试将 Angular DataTable 放入 Boostrap Modal。但是在显示模态时,我得到的 dtElement 是未定义的。这是我的 component.ts,
dtTrigger: Subject<any> = new Subject();
dtOptions: any = {};
@ViewChild(DataTableDirective)
dtElement: DataTableDirective;
modalRef: BsModalRef;
@ViewChild(TemplateRef) entryModal;
ngAfterViewInit() {
this.dtTrigger.next();
}
rerender(): void {
this.dtTrigger.next();
if (this.dtElement.dtInstance) {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
});
} else {
this.dtTrigger.next();
}
}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(
template,Object.assign({},{ class: 'modal-lg' })
);
}
loadMaterials(){
this.materialService.all().subscribe(
response => {
this.materials = response.data;
this.openModal(this.entryModal);
this.changeDetector.detectChanges();
this.rerender();
},error => {
console.log(error);
}
);
}
这是我的组件模板
<ng-template #entryModal>
<div class="card">
<div class="modal-header">
<h4 class="modal-title pull-left text-capitalize">Material Items</h4>
<button
type="button"
class="close pull-right"
aria-label="Close"
(click)="resetModalData()"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<table
datatable
#myTable
[dtOptions]="dtOptions"
[dtTrigger]="dtTrigger"
class="table table-bordered table-striped table-sm"
>
<thead>
<tr>
<th>#</th>
<th>Category</th>
<th>Material</th>
<th>Description</th>
<th>Rate</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let entry of materials; let i = index">
<td>{{ i + 1 }}</td>
<td>{{ entry.material.category.name }}</td>
<td>{{ entry.material.name }}</td>
<td>{{ entry.description }}</td>
<td>{{ entry.rate | customCurrency }}</td>
</tr>
<tr *ngIf="materials && materials.length == 0">
<td colspan="5">No Entries Found!</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-sm btn-default pull-right"
aria-label="Close"
(click)="resetModalData()"
>
<span aria-hidden="true">Close</span>
</button>
</div>
</div>
</ng-template>
在阅读了这些评论中提供的一些问题和参考之后,我认为它未定义的原因是因为它在模板中从未被正确初始化。所以我尝试了 2 个主要建议的选项,
-
在 rerender() 之前调用后使用 ChangeDetectorRef;
-
像这样使用 ViewChild 设置内容
@ViewChild(DataTableDirective) 设置内容(内容:DataTableDirective){ 如果(内容){ this.dtElement = 内容; } }
我还尝试将这些添加到 bs 模式服务的显示事件中。但它都不起作用。我仍然得到 dtElement 未定义。任何的意见都将会有帮助。谢谢。
PS:我使用的是 angular 7,所以不能在 ViewChild 中使用 {static:false} 作为条件模板的建议。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。