角度数据表 - 重新加载数据 [英] Angular Datatables - reload data

查看:26
本文介绍了角度数据表 - 重新加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 angular 6 与 angular-datatables 一起使用.

我尝试定义一个重新渲染"按钮,以便像这个例子一样重新加载数据:

但是当我在重新加载数据后使用这些过滤器时,结果如下:我的不可见列现在可见且页面信息未更新..

这是我的 TS 文件:

//组件视图完全初始化后调用的生命周期钩子ngAfterViewInit() {console.log('ContactsComponent - ngAfterViewInit()');this.dtTrigger.next();this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {//console.log(dtInstance);//console.log(dtInstance.data());dtInstance.columns().every(function () {const 那 = 这个;$('input', this.footer()).on('keyup change', function () {if (that.search() !== this['value']) {that.search(this['value']).画();}});});});}ngOnDestroy(): 无效 {console.log('ngDestroy');//不要忘记取消订阅事件this.dtTrigger.unsubscribe();}重新渲染():无效{this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {dtInstance.columns().every(function () {$('input', this.footer()).val('').change();});//先销毁表dtInstance.destroy();//调用 dtTrigger 重新渲染this.dtTrigger.next();});}

这是我的 dtOptons 配置:

this.dtOptions = {pagingType: 'full_numbers',//显示长度: 10,//serverSide: true,//si true, 执行 l'appel ajax, puis l'exécute à chaque利用 d'un des filtres//处理:真,ajax: (dataTablesParameters: any, callback) =>{console.log('ContactsComponent - 调用 Ajax()');that.selectedList = [];that.http.get('/api/contacts').subscribe(resp => {that.contactList = resp.content;that.loading = false;打回来({数据:that.contactList});},错误 =>{console.log('authService.login error' + error);console.log('错误状态:' + error.status);this.myJarviaServices.showNotification('top', 'center', error,'危险', 1000);this.alertService.error(error);});},//延迟渲染:真,列: [{//标题: '选择',数据:空},{//标题: '标识符',数据:'标识符' } ,{//标题: 'Nom',数据:'nom' },{//标题: 'Prénom',数据:'prenom' },{//标题: '动作',数据:空},{//标题: '动作',数据:'idaicontact'}],列定义:[{可订购:假,//className: 'my_class',//classname définit une checkbox par dessus une case vide [object Object] (data: null)目标:[0],渲染:函数(数据,类型,完整,元){return'<input type="checkbox" class="unique-class mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked ' +'mat-checkbox-inner-container mat-checkbox-inner-container-no-side-margin">';}},{目标:[4],可见:真实,数据:'行动',渲染:函数(数据,类型,完整,元){return '<a class="btn btn-link btn-success btn-just-icon btn-edit" title="编辑器">'+'<i class="material-icons">create</i></a>'+'<a class="btn btn-link btn-danger btn-just-icon btn-remove" title="Supprimer">'+'<i class="material-icons">删除</i></a>'+'<a class="btn btn-link btn-info btn-just-icon btn-read" title="Consulter">'+'<i class="material-icons">可见性</i></a>'}},{目标:[5],可见:假}],rowCallback: (row: Node, data: any[] | Object, index: number) =>{const self = this;//首先解除绑定以避免任何重复的处理程序//(见https://github.com/l-lin/angular-datatables/issues/87)//$('td:first-child', row).unbind('click');//$('td:first-child', row).bind('click', () => {const elt = $('td', row).find('[type="checkbox"]');我感觉) {elt.unbind('点击');elt.bind('点击', () => {如果(elt[0].checked){that.selectedList.push(data as Contact)} 别的 {const itemIndex = this.selectedList.indexOf(data as Contact);that.selectedList.splice(itemIndex, 1);}console.log(that.selectedList.length + 'éléments sélectionés');this.selectedList.forEach((item) => {控制台日志(项目)})});}const eltedit = $('td', row).find('a.btn-edit');如果(eltedit){eltedit.unbind('点击');eltedit.bind('click', () => {控制台日志(数据);this.crudContact(data, 2);});}const eltrem = $('td', row).find('a.btn-remove');如果(eltrem){eltrem.unbind('点击');eltrem.bind('click', () => {this.crudContact(data, 4);});}const eltread = $('td', row).find('a.btn-read');如果(eltread){eltread.unbind('点击');eltread.bind('click', () => {this.crudContact(data, 5);});}返回行;},lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 'Tous']],响应:真实,语: {lengthMenu: 'Afficher _MENU_ enregistrements par page',zeroRecords: 'Aucun 联系方式',信息:'_START_ à _END_ sur un total de _TOTAL_ enregistrements',//info: '页面_PAGE_ sur _PAGES_',infoEmpty: 'Aucun contact disponible',infoFiltered: '(filtré(s) sur _MAX_ enregistrements)',分页:{第一个:'总理',最后一个:'德尼尔',下一个: 'Suvant',上一篇:'先例'},搜索:'_INPUT_',searchPlaceholder: 'Recherche',},顺序:[[1, 'desc']],//在dom参数中声明扩展的使用dom: 'Blfrtip',状态保存:真,纽扣: [{扩展:'打印',className: 'btn btn-info btn-round btn-fab btn-fab-mini',text: '<i class="material-icons" title="Imprimer">print</i>',出口选项:{列:[1, 2, 3]}},{扩展:'pdfHtml5',className: 'btn btn-danger btn-round btn-fab btn-fab-mini',text: '<i class="material-icons" title="Exporter au format pdf">save</i>',出口选项:{列:[1, 2, 3]}},{扩展:'优秀',className: 'btn btn-success btn-round btn-fab btn-fab-mini',text: '<i class="material-icons" title="Exporter au format xls">save</i>',出口选项:{列:[1, 2, 3]}},{text: '<i class="material-icons" title="Supprimer">delete</i>',className: 'btn btn-danger btn-round btn-fab btn-fab-mini',动作:功能(e,dt,节点,配置){that.checkSelect(dt);}},//{//text: '<i class="material-icons" title="Actualiser">replay</i>',//className: 'btn btn-primary btn-round btn-fab btn-fab-mini',//动作:函数(e,dt,节点,配置){//that.refresh();//}//},{text: '<i class="material-icons" title="Nouveau">add</i>',className: 'btn btn-warning btn-round btn-fab btn-fab-mini',动作:功能(e,dt,节点,配置){that.crudContact(null, 1);}}]};

这是我的 HTML 文件:

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%"><!--<table #dataTable class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">--><脚><tr><th>选择</th><!--<th>id</th>--><th><input type="text" placeholder="Recherche Identifiant" name="search-identifiant"/></th><th><input type="text" placeholder="Recherche Nom" name="search-nom"/></th><th><input type="text" placeholder="Recherche prénom" name="search-prenom"/></th><th>Action</th><th>#</th></tr></tfoot><头><tr><th style="width: 1%" ><mat-checkbox (change)="$event ? masterToggle() : null"[checked]="selection.hasValue() &&isAllSelected(contactList.length)"></mat-checkbox></th><th><b>标识符</b></th><th><b>Nom</b></th><th><b>Prenom</b></th><th><b>动作</b></th><th><b>#</b></th></tr></thead>

解决方案

Found !

首先:在方法中移动过滤器代码,示例:

afterView() {this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {//console.log(dtInstance);//console.log(dtInstance.data());dtInstance.columns().every(function () {const 那 = 这个;$('input', this.footer()).on('keyup change', function () {if (that.search() !== this['value']) {that.search(this['value']).画();}});});//dtInstance.on('search.dt', function() {////你有东西吗//console.log('search: ' + dtInstance.search());//});});}

所以当过滤器被应用时,这个方法被调用如下:

 ngAfterViewInit() {console.log('ContactsComponent - ngAfterViewInit()');this.dtTrigger.next();this.afterView();}

当应用过滤器并调用 rerender 方法时,我们必须在加载数据后调用此方法:

 ajax: (dataTablesParameters: any, callback) =>{console.log('ContactsComponent - 调用 Ajax()');that.selectedList = [];that.http.get('/api/contacts').subscribe(resp => {that.contactList = resp.content;that.loading = false;//on charge la tabletelle qu'elle était avant le reloading (filtres éventuels)this.afterView();打回来({数据:that.contactList});},错误 =>{console.log('authService.login error' + error);console.log('错误状态:' + error.status);this.alertService.error(error);this.myJarviaServices.error(error);});},

而且效果很好!

I use angular 6 with angular-datatables.

I try to define a "rerender" button in order to reload data like this exemple :

https://l-lin.github.io/angular-datatables/#/advanced/rerender

My datatable is more complex than the one described in the exemple and I get an issue with individual columns filters use:

This is my table before rerender action with filters use, all works fine:

But when I use these filters after data are reloaded, this is the result : My non-visible column is now visible and page info are not updated..

Here is my TS file :

// Lifecycle hook that is called after a component's view has been fully initialized
ngAfterViewInit() {
    console.log('ContactsComponent - ngAfterViewInit()');
    this.dtTrigger.next();
    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
        // console.log(dtInstance);
        // console.log(dtInstance.data());
        dtInstance.columns().every(function () {
            const that = this;
            $('input', this.footer()).on('keyup change', function () {
                if (that.search() !== this['value']) {
                    that.search(this['value'])
                        .draw();
                }
            });
        });
    });

}
ngOnDestroy(): void {
    console.log('ngDestroy');
    // Do not forget to unsubscribe the event
    this.dtTrigger.unsubscribe();
}
rerender(): void {
    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
        dtInstance.columns().every(function () {
            $('input', this.footer()).val('').change();
        });
        // Destroy the table first
        dtInstance.destroy();
        // Call the dtTrigger to rerender again
        this.dtTrigger.next();
    });
}

Here is my dtOptons config :

this.dtOptions = {
        pagingType: 'full_numbers',
        // displayLength: 10,
        // serverSide: true, // si true, execute l'appel ajax, puis l'exécute à chaque utilisation d'un des filtres
        // processing: true,
        ajax: (dataTablesParameters: any, callback) => {
            console.log('ContactsComponent - call Ajax()');
            that.selectedList = [];
            that.http.get<ApiResponse>('/api/contacts')
                .subscribe(resp => {
                    that.contactList = resp.content;
                    that.loading = false;
                    callback({
                       data: that.contactList
                    });
                },
                error => {
                    console.log('authService.login error' + error);
                        console.log('error status : ' + error.status);
                    this.myJarviaServices.showNotification('top', 'center', error,
                        'danger', 1000);
                    this.alertService.error(error);
                });
        },
        // deferRender: true,
        columns: [
            {
                // title: 'Selection',
                data: null },
            {
                // title: 'Identifiant',
                data: 'identifiant' } ,
            {
                // title: 'Nom',
                data: 'nom' },
            {
                // title: 'Prénom',
                data: 'prenom' }
            ,
            {
                // title: 'Action',
                data: null },
            {
                // title: 'Action',
                data: 'idaicontact'}
        ],
        columnDefs: [
            {
                orderable: false,
                // className: 'my_class', // classname définit une checkbox par dessus une case vide [object Object] (data: null)
                targets: [0],
                render: function(data, type, full, meta) {
                    return'<input type="checkbox" class="unique-class mat-checkbox mat-accent mat-checkbox-anim-checked-unchecked ' +
                        'mat-checkbox-inner-container mat-checkbox-inner-container-no-side-margin">';
                }
            },
            {
                targets: [4],
                visible: true,
                data: 'action',
                render: function(data, type, full, meta) {
                 return '<a class="btn btn-link btn-success btn-just-icon btn-edit" title="Editer">' +
                               '<i class="material-icons">create</i></a>' +
                        '<a class="btn btn-link btn-danger btn-just-icon btn-remove" title="Supprimer">' +
                               '<i class="material-icons">delete</i></a>' +
                        '<a class="btn btn-link btn-info btn-just-icon btn-read" title="Consulter">' +
                              '<i class="material-icons">visibility</i></a>'
                }
            },
            {
                targets: [5],
                visible: false
            }
        ],
        rowCallback: (row: Node, data: any[] | Object, index: number) => {
            const self = this;
            // Unbind first in order to avoid any duplicate handler
            // (see https://github.com/l-lin/angular-datatables/issues/87)
            // $('td:first-child', row).unbind('click');
            // $('td:first-child', row).bind('click', () => {
            const elt = $('td', row).find('[type="checkbox"]');
            if (elt) {
                elt.unbind('click');
                elt.bind('click', () => {
                    if (elt[0].checked) {
                        that.selectedList.push(data as Contact)
                    } else {
                        const itemIndex = this.selectedList.indexOf(data as Contact);
                        that.selectedList.splice(itemIndex, 1);
                    }
                    console.log(that.selectedList.length + ' éléments sélectionés');
                    this.selectedList.forEach((item) => {
                        console.log(item)
                    })
                });
            }
            const eltedit = $('td', row).find('a.btn-edit');
            if (eltedit) {
                eltedit.unbind('click');
                eltedit.bind('click', () => {
                    console.log(data);
                    this.crudContact(data, 2);
                });
            }
            const eltrem = $('td', row).find('a.btn-remove');
            if (eltrem) {
                eltrem.unbind('click');
                eltrem.bind('click', () => {
                    this.crudContact(data, 4);
                });
            }
            const eltread = $('td', row).find('a.btn-read');
            if (eltread) {
                eltread.unbind('click');
                eltread.bind('click', () => {
                    this.crudContact(data, 5);
                });
            }
            return row;
        },
        lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 'Tous']],
        responsive: true,
        language: {
            lengthMenu: 'Afficher _MENU_ enregistrements par page',
            zeroRecords: 'Aucun contact disponible',
            info: '_START_ à _END_ sur un total de _TOTAL_ enregistrements',
            // info: ' Page _PAGE_ sur _PAGES_',
            infoEmpty: 'Aucun contact disponible',
            infoFiltered: '(filtré(s) sur _MAX_ enregistrements)',
            paginate: {
                first:      'Premier',
                last:       'dernier',
                next:       'Suivant',
                previous:   'Precedent'
            },
            search: '_INPUT_',
            searchPlaceholder: 'Recherche',

        },
        order: [[1, 'desc']],
        // Declare the use of the extension in the dom parameter
        dom: 'Blfrtip',
        stateSave: true,
        buttons: [
            {
                extend: 'print',
                className: 'btn btn-info btn-round btn-fab btn-fab-mini',
                text: '<i class="material-icons" title="Imprimer">print</i>',
                exportOptions: {
                    columns: [1, 2, 3]
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
                text: '<i class="material-icons" title="Exporter au format pdf">save</i>',
                exportOptions: {
                    columns: [1, 2, 3]
                }
            },
            {
                extend: 'excel',
                className: 'btn btn-success btn-round btn-fab btn-fab-mini',
                text: '<i class="material-icons" title="Exporter au format xls">save</i>',
                exportOptions: {
                    columns: [1, 2, 3]
                }
            },
            {
                text: '<i class="material-icons" title="Supprimer">delete</i>',
                className: 'btn btn-danger btn-round btn-fab btn-fab-mini',
                action: function (e, dt, node, config) {
                    that.checkSelect(dt);
                }
            },
            // {
            //     text: '<i class="material-icons" title="Actualiser">replay</i>',
            //     className: 'btn btn-primary btn-round btn-fab btn-fab-mini',
            //     action: function (e, dt, node, config) {
            //         that.refresh();
            //     }
            // },
            {
                text: '<i class="material-icons" title="Nouveau">add</i>',
                className: 'btn btn-warning btn-round btn-fab btn-fab-mini',
                action: function (e, dt, node, config) {
                    that.crudContact(null, 1);
                }
            }
        ]
    };

Here is my HTML file :

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
  <!--<table #dataTable class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">-->
  <tfoot>
    <tr>
      <th>Sélection</th>
      <!--<th>id</th>-->
      <th><input type="text" placeholder="Recherche Identifiant" name="search-identifiant"/></th>
      <th><input type="text" placeholder="Recherche Nom" name="search-nom"/></th>
      <th><input type="text" placeholder="Recherche prénom" name="search-prenom"/></th>
      <th>Action</th>
      <th>#</th>
    </tr>
  </tfoot>
  <thead>
    <tr>
      <th style="width: 1%">
        <mat-checkbox (change)="$event ? masterToggle() : null"
          [checked]="selection.hasValue() && isAllSelected(contactList.length)">
        </mat-checkbox>
      </th>
      <th><b>Identifiant</b></th>
      <th><b>Nom</b></th>
      <th><b>Prenom</b></th>
      <th><b>Action</b></th>
      <th><b>#</b></th>
    </tr>
  </thead>
</table>

解决方案

Found !

Firstly : Move filter code in method, example :

afterView() {
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
            // console.log(dtInstance);
            // console.log(dtInstance.data());
            dtInstance.columns().every(function () {
                const that = this;
                $('input', this.footer()).on('keyup change', function () {
                    if (that.search() !== this['value']) {
                        that.search(this['value'])
                            .draw();
                    }
                });
            });
            // dtInstance.on('search.dt', function() {
            //     // Do you stuff
            //     console.log('search: ' + dtInstance.search());
            // });
        });
    }

So when filters are applied, this method is called as following :

 ngAfterViewInit() {
    console.log('ContactsComponent - ngAfterViewInit()');
    this.dtTrigger.next();
    this.afterView();

}

When a filter is applied and that we call rerender method, we must recall this method after loading data :

 ajax: (dataTablesParameters: any, callback) => {
            console.log('ContactsComponent - call Ajax()');
            that.selectedList = [];
            that.http.get<ApiResponse>('/api/contacts')
                .subscribe(resp => {
                        that.contactList = resp.content;
                        that.loading = false;
                        // on charge la table telle qu'elle était avant le reloading (filtres éventuels)
                        this.afterView();
                        callback({
                            data: that.contactList
                        });
                    },
                    error => {
                        console.log('authService.login error' + error);
                        console.log('error status : ' + error.status);
                        this.alertService.error(error);
                        this.myJarviaServices.error(error);
                    });
        },

And it works fine !

这篇关于角度数据表 - 重新加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆