This repository was archived by the owner on Feb 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 489
/
Copy pathangular-datatables.directive.ts
166 lines (148 loc) · 5.34 KB
/
angular-datatables.directive.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://raw.githubusercontent.com/l-lin/angular-datatables/master/LICENSE
*/
import { Directive, ElementRef, Input, OnDestroy, OnInit, Renderer2, ViewContainerRef } from '@angular/core';
import { Subject } from 'rxjs';
import { ADTSettings, ADTColumns } from './models/settings';
import { Api } from 'datatables.net';
@Directive({
selector: '[datatable]',
standalone: false
})
export class DataTableDirective implements OnDestroy, OnInit {
/**
* The DataTable option you pass to configure your table.
*/
@Input()
dtOptions: ADTSettings = {};
/**
* This trigger is used if one wants to trigger manually the DT rendering
* Useful when rendering angular rendered DOM
*/
@Input()
dtTrigger!: Subject<ADTSettings>;
/**
* The DataTable instance built by the jQuery library [DataTables](datatables.net).
*
* It's possible to execute the [DataTables APIs](https://datatables.net/reference/api/) with
* this variable.
*/
dtInstance!: Promise<Api>;
// Only used for destroying the table when destroying this directive
private dt!: Api;
constructor(
private el: ElementRef,
private vcr: ViewContainerRef,
private renderer: Renderer2
) { }
ngOnInit(): void {
if (this.dtTrigger) {
this.dtTrigger.subscribe((options) => {
this.displayTable(options);
});
} else {
this.displayTable(null);
}
}
ngOnDestroy(): void {
if (this.dtTrigger) {
this.dtTrigger.unsubscribe();
}
if (this.dt) {
this.dt.destroy(true);
}
}
private displayTable(dtOptions: ADTSettings | null): void {
// assign new options if provided
if (dtOptions) {
this.dtOptions = dtOptions;
}
this.dtInstance = new Promise((resolve, reject) => {
Promise.resolve(this.dtOptions).then(resolvedDTOptions => {
// validate object
const isTableEmpty = Object.keys(resolvedDTOptions).length === 0 && $('tbody tr', this.el.nativeElement).length === 0;
if (isTableEmpty) {
reject('Both the table and dtOptions cannot be empty');
return;
}
// Set a column unique
if (resolvedDTOptions.columns) {
resolvedDTOptions.columns.forEach(col => {
if ((col.id ?? '').trim() === '') {
col.id = this.getColumnUniqueId();
}
});
}
// Using setTimeout as a "hack" to be "part" of NgZone
setTimeout(() => {
// Assign DT properties here
let options: ADTSettings = {
rowCallback: (row, data, index) => {
if (resolvedDTOptions.columns) {
const columns = resolvedDTOptions.columns;
this.applyNgPipeTransform(row, columns);
this.applyNgRefTemplate(row, columns, data);
}
// run user specified row callback if provided.
if (resolvedDTOptions.rowCallback) {
resolvedDTOptions.rowCallback(row, data, index);
}
}
};
// merge user's config with ours
options = Object.assign({}, resolvedDTOptions, options);
this.dt = $(this.el.nativeElement).DataTable(options);
resolve(this.dt);
});
});
});
}
private applyNgPipeTransform(row: Node, columns: ADTColumns[]): void {
// Filter columns with pipe declared
const colsWithPipe = columns.filter(x => x.ngPipeInstance && !x.ngTemplateRef);
colsWithPipe.forEach(el => {
const pipe = el.ngPipeInstance!;
const pipeArgs = el.ngPipeArgs || [];
// find index of column using `data` attr
const i = columns.filter(c => c.visible !== false).findIndex(e => e.id === el.id);
// get <td> element which holds data using index
const rowFromCol = row.childNodes.item(i);
// Transform data with Pipe and PipeArgs
const rowVal = $(rowFromCol).text();
const rowValAfter = pipe.transform(rowVal, ...pipeArgs);
// Apply transformed string to <td>
$(rowFromCol).text(rowValAfter);
});
}
private applyNgRefTemplate(row: Node, columns: ADTColumns[], data: Object): void {
// Filter columns using `ngTemplateRef`
const colsWithTemplate = columns.filter(x => x.ngTemplateRef && !x.ngPipeInstance);
colsWithTemplate.forEach(el => {
const { ref, context } = el.ngTemplateRef!;
// get <td> element which holds data using index
const i = columns.filter(c => c.visible !== false).findIndex(e => e.id === el.id);
const cellFromIndex = row.childNodes.item(i);
// reset cell before applying transform
$(cellFromIndex).html('');
// render onto DOM
// finalize context to be sent to user
const _context = Object.assign({}, context, context?.userData, {
adtData: data
});
const instance = this.vcr.createEmbeddedView(ref, _context);
this.renderer.appendChild(cellFromIndex, instance.rootNodes[0]);
});
}
private getColumnUniqueId(): string {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 6; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
result += characters.charAt(randomIndex);
}
return result.trim();
}
}