如何在Angular2中的DataTable指令中插入子元素?

时间:2017-01-19 08:40:57

标签: javascript jquery angular jquery-plugins datatables

我制作了一个DataTable指令,我想在其中添加一个子元素。我的问题是,有一段代码需要重复,我不能重复它,因为它的编译方式。请告知如何与此相处,以便我可以打印列表而不是字符串。

DataTable.Directive.ts

import { Directive, Input, OnInit, ElementRef, Inject } from '@angular/core';
import 'datatables.net';

declare var jQuery: any;

@Directive({
    selector: '[dataTable]'
})
export class DataTableDirective implements OnInit {

    /**
     * DataTable options for initiating the DataTables.
     */
    @Input()
    dataTableOptions: any;

    /**
     * Whether the DataTables have a Child Element. A boolean variable for the 
     * same.
     */
    @Input()
    hasChild: Boolean;

    /**
     * Create a instance Variable that will be instantiated
     * for the DataTables
     */
    dataTableInstance: Promise<any>;

    constructor( @Inject(ElementRef) private el: ElementRef) {
        this.dataTableOptions = jQuery.extend(true, {}, jQuery.fn.DataTable.defaults);
    }

    format(d): string {
        // `d` is the original data object for the row
        return `<div class="row">
            <ul>
                <li *ngFor="x in d.client_admin_list">
                    {{x.name}}
                </li>
            </ul>
        </div>`
    }



    ngOnInit() {
        this.dataTableInstance = new Promise((resolve, reject) => {
            Promise.resolve(this.dataTableOptions).then(dtOptions => {

                //Implementing the DataTables by calling it on the host element
                let dt = jQuery(this.el.nativeElement).DataTable(dtOptions);

                //This Variable Refers to the 'this' of the Class. i.e Instance Variable.
                let _thisFuncRef = this;

                if (this.hasChild) {
                    //Adding the Child Grid Functionality if required by the client
                    jQuery(this.el.nativeElement).on('click', 'td.details-control', function () {
                        var tr = jQuery(this).closest('tr');
                        var row = dt.row(tr);
                        if (row.child.isShown()) {
                            // This row is already open - close it
                            row.child.hide();
                            tr.removeClass('shown');
                        }
                        else {
                            // Open this row
                            row.child(_thisFuncRef.format(row.data())).show();
                            tr.addClass('shown');
                        }
                    });
                }
                resolve(dt);
            });
        });
    }
}

输出是这样的 enter image description here

我希望在这种情况下不会发生适当的插值。我很久以来就坚持不懈。

注意:我正在使用DataTables JQuery插件以及带有Typescript的Angular 2.

0 个答案:

没有答案