How to create a common service to integrate jQuery

2019-06-06 06:02发布

问题:

I want to create common service to integrate jQuery datatables(with export buttons) on multiple pages.

I have installed jquery and typings for jquery. Also have included jquery in tsconfig types array.

"types": [
  "jquery"
]

Included required cdn(s) for datatable on index page.

Added an interface JQuery in typings.d.ts :

interface JQuery {
  <dataTable>(options?: any): any;
}

Angular Service :

  ApplyDatatable() {
          $(".mydataTable").dataTable({
                "pagingType": "full_numbers",
                "iDisplayLength": 10,
                bJQueryUI: true,
                "aLengthMenu": [[-1, 10, 20, 50, 100], ["All", 10, 20, 50, 100]],
                select: true,
                "aaSorting": [],
                "aoColumnDefs": [
                  {
                    'bSortable': false,
                    'aTargets': ['disableSorting', 'noExport']
                  }],
                buttons: [
                  {
                    extend: 'collection',
                    text: 'Export',
                    buttons: [
                      //'copy',
                      {
                        extend: 'copyHtml5',
                        exportOptions: {
                          columns: ':visible',
                          columns: "thead th:not(.noExport)"
                        }
                      },
                      {
                        extend: 'csvHtml5',
                        exportOptions: {
                          columns: ':visible',
                          columns: "thead th:not(.noExport)"
                        }
                      }                
                ],         
                dom: 'lfBrtip',    
              }); 
}

Getting error :

jquery__WEBPACK_IMPORTED_MODULE_6__(...).dataTable is not a function (on browser console).

while compiling project getting the error Property 'dataTable' does not exist on type 'JQuery'

回答1:

When using a jQuery plugin, you should create an Angular component as a wrapper for the datatable. Then you can call the jQuery plugin after the component renders.

import { Component, AfterViewInit } from '@angular/core';
import 'jquery';

@Component({
  selector: 'app-datatables',
  ...
})
export class AppDatatables implements AfterViewInit {
  ngAfterViewInit() {
    ($(".mydataTable") as any).dataTable({
      ...
    });
  }
}

Component template:

<div class="mydataTable"></div>

Since you already asked in another question how to render this for every new page(view), that problem is solved now as well, since the component will be re-added every time a new page is loaded/created.