Using full featured Datatables Plugin with Angular 6
Asked Answered
W

8

11

I am trying to add Datatables plugin (datatables.net) facility with my angualar 6 project. I am not sure how should I include the necessary css, js and other required files to my project with npm installer. After selecting my necessary options I am following the NPM Install method with these :

npm install --save datatables.net-bs4
npm install --save datatables.net-buttons-bs4
npm install --save datatables.net-colreorder-bs4
npm install --save datatables.net-responsive-bs4
npm install --save datatables.net-rowgroup-bs4
npm install --save datatables.net-scroller-bs4

After Installing, I am not sure how will I use these in my project. my project is using ngx-bootstrap (https://www.npmjs.com/package/ngx-bootstrap) for styling.

style.scss // where I am only importing my css theme from node_modules

In ngx-bootstrap the styles are component wise, and I am using those easily. So, how can I use datatables features as a component ? In another way, where should I include the css, and required js files to achieve the datatables facilities on a page?

If anyone has done it please let me know, or any suggestions will be appreciated.

Thanks.

Windstorm answered 16/7, 2018 at 14:2 Comment(0)
R
21

use angular data tables in Angular 6 angular-datatables

You need to install its dependencies before getting the latest release using NPM:

npm install jquery --save
npm install datatables.net --save
npm install datatables.net-dt --save
npm install [email protected] --save
npm install @types/jquery --save-dev
npm install @types/datatables.net --save-dev

angular.json

enter image description here

Import the DataTablesModule in app.module.ts

import { DataTablesModule } from 'angular-datatables';

imports: [
    DataTablesModule
  ],

my datatableslibrary.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DataService } from '../data.service';

@Component({
  selector: 'app-datatableslibrary',
  templateUrl: './datatableslibrary.component.html',
  styleUrls: ['./datatableslibrary.component.css']
})
export class DatatableslibraryComponent implements OnInit, OnDestroy {

  users$: any[] = [];
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();

  constructor(private http: HttpClient, private data: DataService) {
  }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      processing: true
    };
    this.data.getUsers().subscribe(data => {
      this.users$ = data;
      this.dtTrigger.next();
    });
  }

  ngOnDestroy(): void {
    this.dtTrigger.unsubscribe();
  }

}

my datatableslibrary.component.html

<table class="table table-striped table-bordered table-sm row-border hover" datatable [dtOptions]="dtOptions"
  [dtTrigger]="dtTrigger">
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Website</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users$">
      <td>{{ user.name }}</td>
      <td>{{ user.email }}</td>
      <td>{{ user.website }}</td>
    </tr>
  </tbody>
</table>

enter image description here

Rust answered 9/9, 2018 at 10:43 Comment(2)
Before answering read full question and all the comments to understand clearly what is the problem. I don't want to use angular-datatables because it does not carry full featured datatable from datatables.net right ?Windstorm
Hey, while implement this got this error ERROR TypeError: $(...).DataTable is not a functionGiffie
C
4

I got DataTables working by doing the following:

angular.json

     "styles": [
          "src/styles.css",
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "node_modules/datatables.net-dt/css/jquery.dataTables.css"
        ],
        "scripts": [
          "node_modules/jquery/dist/jquery.js",
          "node_modules/datatables.net/js/jquery.dataTables.js"
        ]

app.module.ts

        import {DataTablesModule} from 'angular-datatables';


        imports: [
                 ...
                 DataTablesModule
                ]

You may have to stop and re-serve to see changes.

Canescent answered 16/7, 2018 at 16:52 Comment(4)
it's angular-cli.jsonCalefactory
I didn't check the v6. OKCalefactory
@dickrichie Okay, you are using angular-datatable library, I am talking about direct use from datatables files. angular-datatables has pre-made components to use, so in that case you can use it like as you have shown.Windstorm
Whenever i use datatables like this i got error Uncaught ReferenceError: angular is not definedNadia
H
2

Adding DataTablesModule.forRoot() in imports of appmodule.ts works! Or if you are using a lazy loading remember to put it in every module.ts

Homocercal answered 19/2, 2019 at 19:53 Comment(0)
W
1

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ToastrManager } from 'ng6-toastr-notifications';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpParams } from '@angular/common/http';
import { LoginService } from '../login.service';
declare var $;

class SiteModal {
  OrderNumber: string;
  ContactName: string;
  EntityName: string;
  ContactNo: string;
  CategoryName: string;
  StatusName: string;
}

class DataTablesResponse {
  data: any[];
  draw: number;
  recordsFiltered: number;
  recordsTotal: number;
}


@Component({
  selector: 'app-site',
  templateUrl: './site.component.html',
  styleUrls: ['./site.component.scss']
})



export class SiteComponent implements OnInit {
  @ViewChild('dataTable') table: ElementRef;
  dataTable: any;
  dtOptions: DataTables.Settings = {};
  siteModal: SiteModal[];
  dataTablesResponse: DataTablesResponse[];
  datatable: any;
  public data: Object;
  public temp_var: Object = false;

  constructor(
    private http: HttpClient,
    public toastr: ToastrManager,
    private LoginService: LoginService
  ) { }



  ngOnInit(): void {
    const that = this;
  
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10,
      serverSide: true,
      processing: true,
      ordering: false,
      searching: false,


      ajax: (dataTablesParameters: any, callback) => {
        let params = new HttpParams();
        let startNumber: any;

        startNumber = dataTablesParameters.start;
        if (startNumber != 0) {
          startNumber = startNumber + 1
        } else {
          startNumber = startNumber;
        }
        params = params.append("start", startNumber);
        params = params.append("length", dataTablesParameters.length);
        let param = params.toString();
        setTimeout(() => {
          $(".dataTables_empty").hide();
        }, 500);
        that.http
          .post<DataTablesResponse>(
            environment.apiUrl + "api/Entity/GetSiteList",
            params, {}
          ).subscribe(resp => {
            that.siteModal = resp.data;
            debugger
            setTimeout(() => {
              $(".dataTables_empty").hide();
            }, 500);
            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
      },
      columns: [{ data: 'OrderNumber' }, { data: 'ContactName' }, { data: 'EntityName' }, { data: 'ContactNo' }, { data: 'StatusName' }, { data: 'CategoryName' }]
    };


  }

}
<section class="content-header ng-scope">
        <h1>Site </h1>
    </section>
    
    <section class="content">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-12 table-responsive">
                        <table id='Clienttbl' datatable [dtOptions]="dtOptions" class="row-border hover">
                            <thead>
                              <tr>
                                <th>Order #</th>
                                <th>ContactName</th>
                                <th>Entity Name</th>
                                <th>ContactNo</th>
                                <th>StatusName</th>
                                <th>Category Name</th>
                              </tr>
                            </thead>
                            <tbody *ngIf="siteModal?.length != 0">
                                <tr *ngFor="let data of siteModal">
                                    <td>{{ data.OrderNumber }}</td>
                                    <td>{{ data.ContactName }}</td>
                                    <td>{{ data.EntityName }}</td>
                                    <td>{{ data.ContactNo }}</td>
                                    <td>{{ data.StatusName }}</td>
                                    <td>{{ data.CategoryName }}</td>
                                </tr>
                            </tbody>
                          
                          </table> 
    
                    </div>
                </div>
            </div>
        </div>
    </section>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
Waggish answered 17/5, 2019 at 7:12 Comment(1)
Explain it please!Nevski
O
1

Get JSON data from API url

Now you have to play in two components only one is html & other is .ts file

sample.Component.html

<table  id="_zonetable" class="row-border hover" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
   <thead>
   ---
   </thead>
    <tbody>
    <tr  *ngFor="let item of ArrayResponse ; let i=index">
      </tr>
    </tbody>
 </table>

now come to .ts file like sample.Component.ts

import { Component, OnInit ,OnDestroy} from '@angular/core';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
declare var $: any;

now in the export :

export class UtilityComponent implements OnDestroy, OnInit {
dtElement: DataTableDirective;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();



 ngOnInit(): void {
   this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10
    };


ngOnDestroy(): void {
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();

   if ($.fn.DataTable.isDataTable( '#_zonetable' )) {
    //   // call the loader
      $('#_zonetable').dataTable().api().destroy();
    }
  }

  rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // Destroy the table first
      dtInstance.destroy();
      // Call the dtTrigger to rerender again
      // this.dtTrigger.next();
    });
  }

ServiceFunction() {
    this.ArrayResponse=[];
    if ($.fn.DataTable.isDataTable( '#_zonetable' )) {
      //   // call the loader
        $('#_zonetable').dataTable().api().destroy();
      }


this.availservice.JsonAPi()
  .subscribe((json) => {

    this.ArrayResponse = json; //here you will get JSON response
     // Calling the DT trigger to manually render the table
    // debugger;

    if ($.fn.DataTable.isDataTable( '#_zonetable')) {
    //   // call the loader
      $('#_zonetable').dataTable().api().destroy();
        }
        this.dtTrigger.next();
        console.log(this.ArrayResponse);
        setTimeout(() => {
          $('.overlaysv').hide();              
        }, 2000);

      });
  }
Odysseus answered 25/9, 2019 at 7:1 Comment(0)
T
0

By just watching the question and the answer from @dickrichie, I still had an error:

ERROR in node_modules/angular-datatables/src/angular-datatables.directive.d.ts(1
,23): error TS2688: Cannot find type definition file for 'datatables.net'.
node_modules/angular-datatables/src/angular-datatables.directive.d.ts(15,16): er
ror TS2503: Cannot find namespace 'DataTables'.
node_modules/angular-datatables/src/angular-datatables.directive.d.ts(27,25): er
ror TS2503: Cannot find namespace 'DataTables'.

I was missing the two last install steps to make Datatables.net works with Angular 6.

npm install jquery --save
npm install datatables.net --save
npm install datatables.net-dt --save
npm install angular-datatables --save
npm install @types/datatables.net --save-dev

Then follow the message from @dickrichie to edit angular.json and app.module.ts files. Now any table tag where you add "datatable" should work.

-- EDIT

The first part of that answer is with using angular-datatables, but as @fahimuddin asked in fact how to do that without that package, I tried differently.

So no need to install the last two packages, the angular.json looks the same as in @dickrichie answer and in a component I just added before the @Component:

declare var $: any;

And then use directly jQuery and Datatables in ngOnInit():

$('#your-datatable-id').DataTable();

It works and nobody's complaining but I'm not sure if it's a good practice? (And as in my case I'm trying to do an Angular-Electron app, it's still not working in Electron, it wasn't working with angular-datatable neither, but that's another problem!)

Toth answered 8/8, 2018 at 6:16 Comment(8)
I think you have not read my comment on @dickrichie's answer. angular-datatables has some limitations, so that I am trying to use datatables full features from datatables.net importing directly the needed files.Windstorm
Oh yeah you're right, I didn't check all the comments. Sorry about that, looks like you still didn't find a solution. I'll keep digging and will come back to you if I find anything!Toth
@fahimuddin: I just edited my answer, please tell me if it's what you were trying to achieve?Toth
yes that is what I am trying to achieve but I have followed you but it's not working, It's giving this problem > jquery__WEBPACK_IMPORTED_MODULE_3__(...).DataTable is not a functionWindstorm
On this statement :- $('#table_id').DataTable(); ---- Error showing : - .DataTable() does not exist in jQuery<HTMLElement>Windstorm
Looks like you're using Webpack? If you do, I've no clue how to help you further because I don't use and don't know it.Toth
The only thing I can say is that I had an error with Electron saying "jQuery is not defined" and I fixed it by adding: try { window.nodeRequire = require; delete window.require; delete window.exports; delete window.module; }catch (e) {} But don't think it can be related to your error. In your case it seems more than jQuery is loaded but not datatables.net ; you're sure you declare the script in right order?Toth
I thought of this, that my scripts are not in right order, but then I checked and rearranged according some documentations but it's still not working, Can you look on my scripts placing order ? and I also think I will need to use @types/datatables.net , I am not sure about it I will try and let you know the outcomes.Windstorm
D
0

You need to do changes into angular.json file:

"styles": [
    ...
    "node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css",
    ...
],
"scripts": [
    ...
    "node_modules/datatables.net/js/jquery.dataTables.js",
    "node_modules/datatables.net-bs4/js/dataTables.bootstrap4.min.js"
    ...
]

And the same way for extensions plugins.

Dight answered 14/11, 2019 at 12:21 Comment(0)
P
-1

Just add your .css files in styles section and .js files in Scripts section, in angular(-cli).json. I think this would resolve your issues.

Prolongate answered 16/7, 2018 at 14:53 Comment(2)
and for your information, I have angular.json, I don't have angular-cli.json because I am using local angular parsing which has different version than my global angular cli. and I have tried adding that, but it's not working.Windstorm
@FahimUddin both angular-cli.json and angular.json are basically the same. Depending on angular version u will see the corresponding name.Trapezohedron

© 2022 - 2024 — McMap. All rights reserved.