7 votes

How to reload a datatable in angular?

I want that when I press any key in the field filter_field reload the table, I tried with dtOptions.destroy; y dtOptions.renderer; but neither of the 2 reloads the table.

This is the library I am using: link

category.component.html

<blockquote>Haz clic en alguna fila</blockquote>
<p class="text-danger">Hiciste clic en: <strong>{{ message }}</strong></p>
<div class="row">
    <section class="col-md-12">
        <div class="box box-primary">
            <div class="box-body" style="">
                <div class="form-group">
                    <label for="filter_campo" class="control-label col-md-4">Nombre</label>
                    <div class="col-md-8">
                        <input type="text" (keyup)="keyNombre($event.target.value)" class="form-control" id="filter_campo" name="filter_campo">
                    </div>
                </div>
                <div class="form-group">
                    <label for="filter_estados" class="control-label col-md-4">Estado: </label>
                    <div class="col-md-8">
                        <select id='filter_estados' name='filter_estados' class='form-control'>
                            <option value="" disabled="disabled" selected="true">Elija...</option>
                            <option value="true">Activos</option>
                            <option value="false">Inactivos</option>
                            <option value="">Todos</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>
<table datatable [dtOptions]="dtOptions" class="row-border hover"></table>

category.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';

import { CategoriaService } from '../services/categoria.service';
import { Categoria } from '../models/categoria';

@Component({
    selector: 'app-categoria',
    templateUrl: '../views/categoria.component.html',
    styleUrls: ['../styles/categoria.component.css'],
  providers: [CategoriaService]
})
export class CategoriaComponent implements OnInit {

  message = '';
  dtOptions: DataTables.Settings = {};

  public id;
  public categoria: Categoria[];

  constructor(
    private http: HttpClient
  ){
  }

  someClickHandler(info: any): void {
    this.message = info.id + ' - ' + info.nombre;
  }

  nombre = '';
  status = '';

  ngOnInit(): void {
    this.listado();
  }

  keyNombre(e){
    this.nombre = e;
    this.dtOptions.destroy;
    this.dtOptions.renderer;
  }

  listado(){
    this.dtOptions = {
      ajax: {
        url: 'http://localhost/webapp-backend/index.php/categorias/listar',
        type: 'POST',
        global: false,
        method: 'POST',
        data: {
          "json": [
            {
              nombre: this.nombre
            },
            {
              status: this.status
            }
          ]
        }
      },
      columns: [
        {
          data: 0, searchable: false, orderable: false, render: function( data, type, full, meta ){
            return meta.row;
          }
        },
        {
          searchable: false,
          "render": function ( data, type, row ) {
            return row.nombre;
          }
        },
        {
          searchable: false,
          "render": function ( data, type, row ) {
            if(row.status){
              return 'Activo';
            }else{
              return 'Inactivo';
            }
          }
        },
      ],
      order: [[1, 'asc']],
      rowCallback: (row: Node, data: any[] | Object, index: number) => {
        const self = this;
        $('td', row).unbind('click');
        $('td', row).bind('click', () => {
          self.someClickHandler(data);
        });
        return row;
      },
      initComplete: function (data) {
      },
      responsive: true
    };
  }
}

Update 1:

Using httpClient :

Typescript :

that.http
  .post(
    this.url+'categorias/listar',
    {
        "nombre": this.categorias.nombre,
        "status": this.categorias.status,
    }
  ).subscribe(resp => {

    callback({
      recordsTotal: resp.data.length,
      recordsFiltered: resp.data.length,
      data: resp.data
    });
  });

PHP :

$app->post("/categorias/listar", function() use($app, $db){
    $method = $app->request()->getBody();
    $data = json_decode($method, true);
    $sql  = '';
    $sql .= "SELECT * FROM categorias AS c ";
    if(($data['nombre'] != '')||($data['nombre'] != null)){
        $sql .= "WHERE nombre='".$data['nombre']."'";
    }
    $sql .= " ORDER BY nombre";

    try {

        $stmt = $db->query($sql);
        $tables = [];
        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $tables[] = $row;
        }
        $result = array(
            'status' => 'success',
            'code' => 200,
            'data' => $tables,
        );
        echo json_encode($result);
    } catch (\PDOException $e) {
        echo json_encode($e->getMessage());
    }
});

The problem I have is pagination: error

0 votes

Why do you use ajax instead of an angular http provider? the code should be encapsulated inside a service returning an observable.

1 votes

@cardeol with http provider I had problems, I did not know how to use it, if you give me an example adapted to my needs, I welcome it.

0 votes

@PabloContreras and have you already tried filtering? ==> l-lin.github.io/angular-datatables/#/advanced/…

6voto

jarios Points 542

Based on the example of Custom filtering I think it should work something like this:

export class CategoriaComponent implements OnInit {

    message = '';
    dtOptions: DataTables.Settings = {};

    datatableElement: DataTableDirective;  // <== 

    keyNombre(e){                          // <== 
      this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
        dtInstance.draw();
      });
    }

}

As for the column ordering, in the column definition you have: "orderable: false"

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X