How to reload a datatables in angular?

7

I want that when I press any key in the field filter_campo recharge the table, I tried with dtOptions.destroy; and dtOptions.renderer; but none of the 2 recharges the table.

This is the library I'm using: link

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

categoria.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 link :

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 the paging:

    
asked by Pablo Contreras 20.09.2018 в 22:49
source

1 answer

6

Based on the example of Custom filtering , I think that you something like this should work:

export class CategoriaComponent implements OnInit {
    
    message = '';
    dtOptions: DataTables.Settings = {};
    
    datatableElement: DataTableDirective;  // <== 

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

Regarding the ordering of columns, in the definition of them you have: "orderable: false"

    
answered by 27.09.2018 / 09:57
source