'Angular DataTables: $(...).DataTable is not a function
Angular Version: 6.0.4 ~ Node Version: 10.4.1 ~ NPM Version: 6.1.0
I've seen this question asked many times, but not answered.
After following these instructions to install angular-datables, and trying to use the directive on a table, as in their Zero Configuration example, I keep getting this error:
TypeError: $(...).DataTable is not a function
at angular-datatables.directive.js:42
Included Styles and Scripts
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/datatables.net-dt/css/jquery.dataTables.css",
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
"node_modules/datatables.net/js/jquery.dataTables.js"
]
Import in app.module.ts
import { DataTablesModule } from 'angular-datatables';
DataTablesModule is added to array of imports.
*.component.html
<h1>View Accounts</h1>
<table class='table table-dark text-center table-striped table-hover rounded' datatable>
<thead class='thead-dark'>
<tr>
<td>#</td>
<td>Account Name</td>
</tr>
</thead>
<tbody>
<tr *ngFor='let account of db.accounts; let i = index' routerLink='/account/{{account.id}}'>
<td>{{i+1}}</td>
<td>{{account.accountHolder}}</td>
</tr>
</tbody>
</table>
Solution 1:[1]
Angular version(9 and above):
component.ts
------------
import * as $ from 'jquery';
import 'datatables.net';
import { from, Subject } from 'rxjs';
export class testComponent implements OnInit {
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
}
component.html
--------------
<table [dtTrigger]="dtTrigger" id="example" datatable class="row-border hover">
<thead><tr><th></th></tr></thead>
<tbody>....</tbody>
<table>
Solution 2:[2]
I was missing ' "node_modules/datatables.net/js/jquery.dataTables.js", ' in angular.json It should look like
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/datatables.net/js/jquery.dataTables.js",
"node_modules/bootstrap/dist/js/bootstrap.js"
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arun |
| Solution 2 | Bill8080 |
