angularangular-datatables

How to select all checkbox in Datatables, Angular


I am using Datatable in Angular, and I want to use select all checkboxes functionality in that grid. I tried with below code but getting error

onselectAll(){
    this.dtTrigger.next();
    this.datatableElement.dtInstance.then((dtInstance: any) => {
      dtInstance.rows().select();
      this.dtTrigger.next();
    });    
}

error : TypeError: dtInstance.rows(...).select is not a function

Function for intialising datatable :

bindDataTable() {

var that = this;
this.dtOptions = {
  order: [[1, 'asc']],
  lengthMenu: [10, 25, 50, 75, 100],
  language: { paginate: { next: '→', previous: '←', first: '', last: '' }, searchPlaceholder: "Search here....", search: "" },
  info: false,
  // dom: "Rlfrtip",
  dom: 'Bfrtip',
  rowGroup: {
    dataSrc: 'group'
},
  select: {
    style: 'os',
    selector: 'td:first-child'
  },
  columnDefs: [{
    targets: 0,
    width: 20,
    orderable: false,
    className: 'select-checkbox'
  },
  {
    targets: 1,

  }
  ],
  serverSide: true,
  processing: true,
  ajax: (dataTablesParameters: any, callback) => {
    that.spinner.show();
    var start = dataTablesParameters.start;
    var recsPerPage = dataTablesParameters.length;
    var search = dataTablesParameters.search.value;
    var sortColumn = dataTablesParameters.order[0].column;
    var sortOrder = dataTablesParameters.order[0].dir;
    var orderby = "";
    this.baseAPIService.post<any[]>("/url",
      {
        "category_id": this.categoryIDs,
        "product_name": this.productNames,
        "search_text": "",
        "sku": this.skuList,
        "shop_id": this.model.shopId_screen,
        "vendor_id": this.vendorId
      })
      .subscribe(resp => {
        this.spinner.hide();
        this.productList = resp['data'];

        callback({
          recordsTotal: resp['count'],
          recordsFiltered: resp['count'],
          data: resp['data']
        });

        var btnEdits: any = document.getElementsByClassName("btnEdit");
        for (let btn of btnEdits) {
          btn.onclick = (event) => {
            var id = btn.getAttribute("data-id");
           
              $("#txt-final_stock-" + id).hide();       //final stock
              $("#spn-final_stock-" + id).text(final).show();
            }
            $("#txt-is_selected-" + id).attr('checked', 'checked');
            $("#btnEdit-" + id).hide();
            $("#btnSave-" + id).show();
            $("#btnCancel-" + id).show();
          }
        }

        var btnSaves: any = document.getElementsByClassName("btnSave");
        for (let btn of btnSaves) {
          btn.onclick = (event) => {
            var id = btn.getAttribute("data-id");
            $("#btnEdit-" + id).show();
            $("#btnSave-" + id).hide();
            $("#btnCancel-" + id).hide();
            })

          }
        }

        var btnCancels: any = document.getElementsByClassName("btnCancel");
        for (let btn of btnCancels) {
          btn.onclick = (event) => {
            var id = btn.getAttribute("data-id");
            $("#spn-final_stock-" + id).show();

            $("#txt-final_stock-" + id).hide();

            $("#btnEdit-" + id).show();
            $("#btnSave-" + id).hide();
            $("#btnCancel-" + id).hide();
          }
        }

        var btnSelectedProducts: any = document.getElementsByClassName("chkProduct");
        for (let btn of btnSelectedProducts) {
          btn.onclick = (event) => {
            var id = btn.getAttribute("data-id");
            var isSelected = $("#txt-is_selected-" + id).is(":checked");

            var model = this.updatedProducts.filter(x => x.varientid == id);
            if (model.length == 0) {
              model = this.products.filter(x => x.varientid == id);
              this.updatedProducts.push(model[0]);
            }
            this.updatedProducts.filter(x => x.varientid == id).map(x => x['is_selected'] = isSelected);

          }
        }
      },
        error => {
          this.spinner.hide();
          callback({
            recordsTotal: 0,
            recordsFiltered: 0,
            data: []
          });
        })
  },


  columns: [
    {
      data: null, orderable: false, render: (data, type, row, meta) => {
        var isSelected = false;
        var model = this.updatedProducts.filter(x => x.varientid == row.varientid);
        if (model.length == 0) {
          model = this.products.filter(x => x.varientid == row.varientid);
        }

        if (model.length > 0 && model[0]['is_selected'] == true) {
          return '<div class="form-check col-md-6 text-center p-0 m-0 mt-1 s-info">' +
            '<input type="checkbox" class="form-check-input chkProduct" checked data-id="' + row.varientid + '" id="txt-is_selected-' + row.varientid + '">' +
            '</div>';
        } else {
          return '<div class="form-check col-md-6 text-center p-0 m-0 mt-1 s-info">' +
            '<input type="checkbox" class="form-check-input chkProduct" data-id="' + row.varientid + '" id="txt-is_selected-' + row.varientid + '">' +
            '</div>';
        }
      }
    },
    { data: "productname" },
    { data: "brandname" },
    { data: 'sku' },
    { data: "varient_sku" },
    { data: "varientid" },
    {
      orderable: false,
      className: "text-center",
      render: (data, type, row, meta) => {
        return '<a class="text-center btnEdit" id="btnEdit-' + row.varientid + '" data-id="' + row.varientid + '"><svg  width="18px" height="18px" id="data-edit"></svg></a>&nbsp;&nbsp;' +
          '<a class="text-center btnSave" id="btnSave-' + row.varientid + '" style="display:none;" data-id="' + row.varientid + '"><svg width="18px" height="18px" enable-background="new 0 0 512.007 512.007" height="512"</svg></a>' +
          '&nbsp;&nbsp;<a class="text-center btnCancel" id="btnCancel-' + row.varientid + '" style="display:none;" data-id="' + row.varientid + '"><svg width="13px" height="13px" id="data-delete">'
      }
    }

  ]
};

}

HTML :

 <table id="stock-table" class="table row-border table-responsive hover"
        datatable [dtOptions]="dtOptions">
    <thead>
      <tr>
        <th class="select-checkbox"><input id="checkBox" type="checkbox" (click)="onselectAll()"></th>
        <th>Product Name</th>
        <th>Brand</th>
        <th>SKU Code</th>
        <th>Varient SKU</th>
        <th>Varient</th>
        <th>Current stock</th>
        <th>Final Stock</th>
        <th>Update/Cancel</th>
      </tr>
   </thead>
   <tbody>

   </tbody>
</table>

please give me some solutions, how can i resolve this issue.


Solution

  • I got solution from this link Angular 6 - Datatables

    onselectAll(){
     
        this.dtTrigger.next();
        this.datatableElement.dtInstance.then((dtInstance: any) => {
          this.isAllChecked = $('th', dtInstance.table(0).node()).find('[type="checkbox"]')[0]['checked'];
          var elts = [];
          $('td', dtInstance.table(0).node()).find('[type="checkbox"]')
          var el = $('td', dtInstance.table(0).node()).find('[type="checkbox"]')
          elts.push(el)
          var temp = elts[0]
          for (const elt of temp) {
            elt.checked = this.isAllChecked;
            //$("#txt-is_selected-" + elt.dataset['id']).attr('checked', 'checked');     
        };
        });       
    }