在Angular 6中使用功能齐全的Datatables插件

时间:2018-07-16 14:02:54

标签: angular datatables angular-datatables ngx-bootstrap

我正在尝试在我的angualar 6项目中添加Datatables插件(datatables.net)工具。 我不确定如何使用npm installer将必要的css,js和其他必需文件包含到我的项目中。 选择必要的选项后,我将使用以下NPM Install方法:

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

安装后,我不确定如何在项目中使用它们。我的项目正在使用ngx-bootstrap(https://www.npmjs.com/package/ngx-bootstrap)进行样式设置。

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

在ngx-bootstrap中,样式是基于组件的,我很容易使用它们。 因此,如何将数据表功能用作组件? 换句话说,我应该在哪里包括CSS和必需的js文件,以实现页面上的数据表功能?

如果有人这样做,请告诉我,否则我们将不胜感激。

谢谢。

9 个答案:

答案 0 :(得分:11)

在Angular 6 angular-datatables中使用角度数据表

您需要先安装其依赖项,然后才能使用NPM获取最新版本:

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

angular.json

enter image description here

在app.module.ts中导入DataTablesModule

import { DataTablesModule } from 'angular-datatables';

imports: [
    DataTablesModule
  ],

我的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();
  }

}

我的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

答案 1 :(得分:1)

我通过执行以下操作使DataTables工作:

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
                ]

您可能必须停下来再准备好才能看到更改。

答案 2 :(得分:0)

只需将您的.css文件添加到styles部分中,并将.js文件添加到Scripts部分中,并添加到angular(-cli).json中。我认为这可以解决您的问题。

答案 3 :(得分:0)

您可以在此处找到完整的答案:https://medium.com/apprendre-le-web-avec-lior/angular-5-and-jquery-datatables-fd1dd2d81d99

按照以下步骤操作,您就可以了

答案 4 :(得分:0)

仅观看@dickrichie的问题和答案,我仍然有一个错误:

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'.

我错过了使Datatables.net与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

然后按照@dickrichie的消息来编辑angular.json和app.module.ts文件。现在,任何添加“数据表”的表标签都可以使用。

-编辑

答案的第一部分是使用angular-datatables,但是正如@fahimuddin问的那样,如果没有该软件包,该怎么做,我尝试了不同的方法。

因此无需安装最后两个软件包,angular.json看起来与@dickrichie答案以及我刚刚在@Component之前添加的组件中的相同:

declare var $: any;

然后在ngOnInit()中直接使用jQuery和Datatables:

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

它有效并且没有人抱怨,但是我不确定这是否是一个好习惯? (就我而言,我正在尝试开发一个Angular-Electron应用程序,它仍然无法在Electron中工作,它也没有使用angular-datatable,但这是另一个问题!)

答案 5 :(得分:0)

DataTablesModule.forRoot()的导入中添加appmodule.ts是可行的!或者,如果您使用的是延迟加载,请记住将其放入每个module.ts

答案 6 :(得分:0)

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>

答案 7 :(得分:0)

  

从API网址获取JSON数据

现在您必须扮演两个角色,一个是html,另一个是.ts文件

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>

现在进入.ts文件,例如 sample.Component.ts

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

现在在导出中:

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);

      });
  }

答案 8 :(得分:0)

您需要对angular.json文件进行更改:

"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"
    ...
]

与扩展插件相同。