I'm trying to write a Lightning Web Component which uses jquery and datatable static resources and getting an annoying error message without any idea how to solve it.
My html code is:
<div class="slds-box">
<h1 style="vertical-align: super;font-size: 18px;">TEXT</h1>
<br></br>
<table id="tableId" class="example">
<thead>
<tr class="slds-text-heading_label">
<th class="thIndex" scope="col"><div class="slds-truncate" title="TEXT">TEXT</div></th>
<th scope="col"><div class="slds-truncate" title="TEXT">TEXT</div></th>
<th scope="col"><div class="slds-truncate" title="TEXT">TEXT</div></th>
</tr>
</thead>
<tbody>
<template for:each={list} for:item='emp' for:index='indx'>
<tr key={emp.Id}>
<th scope="row"><div class="slds-truncate">{indx}</div></th>
<th scope="row"><div class="slds-truncate">TEXT</div></th>
<th scope="row"><div class="slds-truncate">TEXT</div></th>
</tr>
</template>
</tbody>
</table>
</div>
My JavaScript (part of) code is:
import { loadScript,loadStyle } from 'lightning/platformResourceLoader';
import { LightningElement,track,api,wire } from 'lwc';
import datatableAS from '@salesforce/resourceUrl/compsuite__datatable';
import jQuery from '@salesforce/resourceUrl/compsuite__jquery224';
export default class Lwc_Curriculum_Training_Report extends NavigationMixin(LightningElement) {
dataTablejsInitialized = false;
renderedCallback() {
if (this.dataTablejsInitialized) {
return;
}
this.dataTablejsInitialized = true;
loadScript(this,jQuery)
.then(()=>{
Promise.all([
loadScript(this, ChartJS)
loadScript(this, datatableAS+'/DataTables-
1.10.18/js/jquery.dataTables.min.js'),
loadStyle(this, datatableAS+'/DataTables-
1.10.18/css/jquery.dataTables.min.css')
])
.then(()=>{
this.template.querySelector('.example').DataTable();
})
})
.catch(error => {
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading DataTables',
message: error.message,
variant: 'error'
})
);
});
}
When the component is rendered, an error message is displayed in the console:
null TypeError: this.template.querySelector(...).DataTable is not a function
at eval (lwc_Curriculum_Training_Report.js:4)
(anonymous) @ aura_prod.map.js:46726
t.$$lwcEventWrapper$$ @ lwc_engine.js:3211
lwc_Curriculum_Training_Report.js:4 Uncaught (in promise) TypeError:
this.template.querySelector(...).DataTable is not a function
at eval (lwc_Curriculum_Training_Report.js:4)
It's important to mention that I tried .DataTable,.dataTable,.datatable and .Datatable, nothing worked. In addition the Static Resources loaded properly which means the problem is not about the path of the resources, it's about how to initialize the DataTable, which method/command/code should be written.
I hope someone could help me.
EDIT: I tried to load the jQuery in promise as well. Additionally, these static resources work in lightning components I've written before, the problem invokes just for lightning web component.