Angular 6 - 数据表 [英] Angular 6 - Datatables

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

问题描述

我使用带有复选框的 Angular-Datatables(最新版本)

I use Angular-Datatables (latest version) with checkboxes

我想定义一个全选"功能.但我不知道如何将所有复选框标记为已选中":

and I would like to define a "Select All" function. But I don't know how to mark as "checked" all the checkboxes :

创建的所有示例都是使用 Angular JS 或 Jquery 开发的,但是当我阅读文档时,它似乎不是这样工作的.

All examples founded are developed with Angular JS or Jquery but when I read documentation it seems it doesn't work like this way.

我认为(我可能错了)正确的方法是使用 this.datatableElement.dtInstance.

I think (I may be wrong) the correct way is to use this.datatableElement.dtInstance.

我已经用它来实现单个列过滤选项:https://l-lin.github.io/角度数据表/#/advanced/individual-column-filtering

I already use it to implement individual columns filtering option : https://l-lin.github.io/angular-datatables/#/advanced/individual-column-filtering

所以我想我必须保留它.

So I think I must keep it.

我的 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%">-->
                            <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>
                                </tr>
                            </tfoot>
                            <thead>
                                <tr>
                                    <th style="width: 1%">
                                        <input type="checkbox" (click)="masterToggle($event)">
                                    </th>
                                    <!--<th style="width: 1%">-->
                                        <!--<mat-checkbox (change)="$event ? masterToggle($event) : null"-->
                                        <!--[checked]="selection.hasValue() && isAllSelected(contactList.length)">-->
                                        <!--</mat-checkbox>-->
                                    <!--</th>-->
                                    <th>Identifiant</th>
                                    <th>Nom</th>
                                    <th>Prenom</th>
                                    <th>Action</th>
                                </tr>
                            </thead>

但是我不知道如何实现 masterToggle() 函数...

But I don't know how to implement masterToggle() function...

我的 dtOptions 配置:

My dtOptions configuration :

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()');
                // console.log(dataTablesParameters);
                that.http.get<ApiResponse>('/api/contacts')
                    .subscribe(resp => {
                        that.contactList = resp.content;
                        // console.log(that.contactList);
                        that.loading = false;
                        callback({
                            // recordsTotal: resp.totalElements,
                            // recordsFiltered: resp.totalElements,
                            // recordsFiltered: 0,
                            // data: []
                           data: that.contactList
                        });
                    });
            },
 columns: [
                {
                    // title: 'Selection',
                    data: null },
                // {
                //     title: 'N°',
                //     data: 'idaicontact' },
                {
                    // title: 'Identifiant',
                    data: 'identifiant' } ,
                {
                    // title: 'Nom',
                    data: 'nom' },
                {
                    // title: 'Prénom',
                    data: 'prenom' }
                ,
                {
                    // title: 'Action',
                    data: null }
            ],
columnDefs: [
                {
                    orderable: false,
                    // className: 'select-checkbox', // 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" ">';

                        // return ' <mat-checkbox (change)="$event ? masterToggle($event) : null"' +
                        //     '[checked]="selection.hasValue() && isAllSelected(contactList.length)">' +
                        //     '</mat-checkbox>'
                    }
                },
]
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) {
                            console.log((data as Contact).identifiant + ' a été sélectionné');
                        } else {
                            console.log((data as Contact).identifiant + ' a été déselectionné');
                        }
                        // self.someClickHandler(row, data, index);
                    });
                }

单个列过滤使用 dtInstance :

Indivudual column filtering uses dtInstance :

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();
                    }
                });
            });
            // dtInstance.on('search.dt', function() {
            //     // Do you stuff
            //     console.log('search: ' + dtInstance.search());
            // });
        });

    }

但是我如何将它用于我的复选框?

But how can I use it for my checkboxes ?

更新我已经找到了解决方案:

UPDATE I have almont found the solution :

this.isAllChecked = $('th', dtInstance.table(0).node()).find('[type="checkbox"]')[0].checked;
            console.log('Select All: ' + this.isAllChecked);
            let elts: any[] = [];
            $('td', dtInstance.table(0).node()).find('[type="checkbox"]') // renvoie la valeur des checkbox uniquement pour les
            // lignes affichées !!
            elts = $('td', dtInstance.table(0).node()).find('[type="checkbox"]');
            for (const elt of elts) {
                elt.checked = this.isAllChecked;
            };

最后一个问题是只更新了第一页的复选框...

The last problem is that only the checkboxes of the first page are updated...

推荐答案

我不喜欢这种 jquery 乱七八糟",所以我做了这个 stackblitz 来展示另一种可能的解决方案,从我的角度来看,这更好.

I am not a fan of such jquery "messing", so I made this stackblitz to show one more possible solution, which is much better from my point of view.

首先,您需要为您的数据项实现检查绑定,以使您的生活更轻松.

First of all you need to implement check binding for you data items to make you life easier.

就您使用服务器端处理而言,您需要在客户端存储已检查的状态,并在每次数据请求后相应地更新 checked 属性(isPersonChecked 方法).为此,有两个数组:checkedPersonIds - 未设置全部检查"标志时放置已选中项目的位置,uncheckedPersonIds - 设置全部检查"标志时放置未选中项目的位置.这就是您跟踪已检查"状态所需的全部内容.

As far as you use server side processing you need to store checked state on client, updating checked property accordingly after each data request (isPersonChecked method). For this purpose there are two arrays: checkedPersonIds - where you put checked items when "check all" flag is unset and uncheckedPersonIds - where you put unchecked items when "check all" flag is set. That's all you need to track "checked" state.

希望这会对某人有所帮助.

Hope this will help someone.

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

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