angular2-data-table
Version:
angular2-data-table is a Angular2 component for presenting large and complex data.
186 lines (156 loc) • 4.13 kB
text/typescript
import {
Component, Input, PipeTransform, HostBinding,
Output, EventEmitter, HostListener, ElementRef
} from '@angular/core';
import { deepValueGetter, Keys } from '../../utils';
import { SortDirection } from '../../types';
export class DataTableBodyCellComponent {
row: any;
column: any;
rowHeight: number;
isSelected: boolean;
set sorts(val: any[]) {
this._sorts = val;
this.calcSortDir = this.calcSortDir(val);
}
get sorts(): any[] {
return this._sorts;
}
activate: EventEmitter<any> = new EventEmitter();
isFocused: boolean = false;
get isSortActive(): boolean {
return !this.sortDir;
}
get isSortAscending(): boolean {
return this.sortDir === SortDirection.asc;
}
get isSortDescending(): boolean {
return this.sortDir === SortDirection.desc;
}
get width(): number {
return this.column.width;
}
get height(): string|number {
const height = this.rowHeight;
if(isNaN(height)) return height;
return height + 'px';
}
get value(): any {
if (!this.row || !this.column || !this.column.prop) return '';
const val = deepValueGetter(this.row, this.column.prop);
const userPipe: PipeTransform = this.column.pipe;
if(userPipe) return userPipe.transform(val);
if(val !== undefined) return val;
return '';
}
sortDir: SortDirection;
element: any;
_sorts: any[];
constructor(element: ElementRef) {
this.element = element.nativeElement;
}
onFocus(): void {
this.isFocused = true;
}
onBlur(): void {
this.isFocused = false;
}
onClick(event: MouseEvent): void {
this.activate.emit({
type: 'click',
event,
row: this.row,
column: this.column,
value: this.value,
cellElement: this.element
});
}
onDblClick(event: MouseEvent): void {
this.activate.emit({
type: 'dblclick',
event,
row: this.row,
column: this.column,
value: this.value,
cellElement: this.element
});
}
onKeyDown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
const isTargetCell = event.target === this.element;
const isAction =
keyCode === Keys.return ||
keyCode === Keys.down ||
keyCode === Keys.up ||
keyCode === Keys.left ||
keyCode === Keys.right;
if(isAction && isTargetCell) {
event.preventDefault();
event.stopPropagation();
this.activate.emit({
type: 'keydown',
event,
row: this.row,
column: this.column,
value: this.value,
cellElement: this.element
});
}
}
onCheckboxChange(event): void {
this.activate.emit({
type: 'checkbox',
event,
row: this.row,
column: this.column,
value: this.value,
cellElement: this.element
});
}
calcSortDir(sorts: any[]): any {
if(!sorts) return;
const sort = sorts.find((s: any) => {
return s.prop === this.column.prop;
});
if(sort) return sort.dir;
}
}