-
Notifications
You must be signed in to change notification settings - Fork 25.3k
/
table.ts
72 lines (65 loc) · 1.93 KB
/
table.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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {TableCell} from '../util';
export class TableComponent {
private _renderCells: any[][];
constructor(private _rootEl: any) {}
set data(data: TableCell[][]) {
if (data.length === 0) {
this._destroy();
} else if (this._renderCells) {
this._update(data);
} else {
this._create(data);
}
}
private _destroy() {
while (this._rootEl.lastChild) {
this._rootEl.lastChild.remove();
}
this._renderCells = null;
}
private _update(data: TableCell[][]) {
for (let r = 0; r < data.length; r++) {
const dataRow = data[r];
const renderRow = this._renderCells[r];
for (let c = 0; c < dataRow.length; c++) {
const dataCell = dataRow[c];
const renderCell = renderRow[c];
this._updateCell(renderCell, dataCell);
}
}
}
private _updateCell(renderCell: any, dataCell: TableCell) {
renderCell.textContent = dataCell.value;
}
private _create(data: TableCell[][]) {
const table = document.createElement('table');
this._rootEl.appendChild(table);
const tbody = document.createElement('tbody');
table.appendChild(tbody);
this._renderCells = [];
for (let r = 0; r < data.length; r++) {
const dataRow = data[r];
const tr = document.createElement('tr');
tbody.appendChild(tr);
const renderRow = [];
this._renderCells[r] = renderRow;
for (let c = 0; c < dataRow.length; c++) {
const dataCell = dataRow[c];
const renderCell = document.createElement('td');
if (r % 2 === 0) {
renderCell.style.backgroundColor = 'grey';
}
tr.appendChild(renderCell);
renderRow[c] = renderCell;
this._updateCell(renderCell, dataCell);
}
}
}
}