代码之家  ›  专栏  ›  技术社区  ›  anakin59490

角度6-数据表

  •  0
  • anakin59490  · 技术社区  · 6 年前

    我想定义一个“全选”函数。 但我不知道如何标记为“选中”所有复选框:

    enter image description here

    所有的例子都是用angularjs或Jquery开发的,但是当我阅读文档时,它似乎不是这样工作的。

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

    我已经使用它来实现单个列过滤选项: https://l-lin.github.io/angular-datatables/#/advanced/individual-column-filtering

    所以我想我必须保留它。

    我的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()函数。。。

    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:

    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());
                // });
            });
    
        }
    

    但是我怎么用它来做我的复选框呢?

    我找到了解决办法:

    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;
                };
    

    最后一个问题是只有第一页的复选框被更新。。。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Petr Pokrovskiy    5 年前

    我不喜欢这种jquery“混乱”,所以我做了这个 stackblitz

    首先,您需要为您的数据项实现检查绑定,以使您的工作更轻松。

    checked 每次数据请求后相应地( isPersonChecked 方法)。为此,有两个阵列: checkedPersonIds uncheckedPersonIds -设置“全部检查”标志时放置未检查项的位置。这就是你所需要的跟踪“检查”状态。

    推荐文章