UNPKG

primeng

Version:

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![npm version](https://badge.fury.io/js/primeng.svg)](https://badge.fury.io/js/primeng) [![npm downloads](https://img.shields.io/npm/dm/primeng.sv

1,210 lines (1,209 loc) 232 kB
import * as i0 from '@angular/core'; import { Injectable, EventEmitter, Component, ChangeDetectionStrategy, ViewEncapsulation, Input, Output, ViewChild, ContentChildren, Directive, HostListener, Optional, NgModule } from '@angular/core'; import * as i3 from '@angular/common'; import { CommonModule } from '@angular/common'; import * as i9 from '@angular/forms'; import { FormsModule } from '@angular/forms'; import * as i1 from 'primeng/api'; import { FilterOperator, FilterMatchMode, PrimeTemplate, TranslationKeys, SharedModule } from 'primeng/api'; import * as i2 from 'primeng/paginator'; import { PaginatorModule } from 'primeng/paginator'; import * as i8 from 'primeng/inputtext'; import { InputTextModule } from 'primeng/inputtext'; import * as i11 from 'primeng/button'; import { ButtonModule } from 'primeng/button'; import { SelectButtonModule } from 'primeng/selectbutton'; import * as i6 from 'primeng/tristatecheckbox'; import { TriStateCheckboxModule } from 'primeng/tristatecheckbox'; import * as i7 from 'primeng/calendar'; import { CalendarModule } from 'primeng/calendar'; import * as i5 from 'primeng/inputnumber'; import { InputNumberModule } from 'primeng/inputnumber'; import * as i10 from 'primeng/dropdown'; import { DropdownModule } from 'primeng/dropdown'; import { DomHandler, ConnectedOverlayScrollHandler } from 'primeng/dom'; import { ObjectUtils } from 'primeng/utils'; import { Subject } from 'rxjs'; import * as i4 from '@angular/cdk/scrolling'; import { CdkVirtualScrollViewport, ScrollingModule } from '@angular/cdk/scrolling'; import { trigger, transition, style, animate } from '@angular/animations'; class TableService { constructor() { this.sortSource = new Subject(); this.selectionSource = new Subject(); this.contextMenuSource = new Subject(); this.valueSource = new Subject(); this.totalRecordsSource = new Subject(); this.columnsSource = new Subject(); this.resetSource = new Subject(); this.sortSource$ = this.sortSource.asObservable(); this.selectionSource$ = this.selectionSource.asObservable(); this.contextMenuSource$ = this.contextMenuSource.asObservable(); this.valueSource$ = this.valueSource.asObservable(); this.totalRecordsSource$ = this.totalRecordsSource.asObservable(); this.columnsSource$ = this.columnsSource.asObservable(); this.resetSource$ = this.resetSource.asObservable(); } onSort(sortMeta) { this.sortSource.next(sortMeta); } onSelectionChange() { this.selectionSource.next(); } onResetChange() { this.resetSource.next(); } onContextMenu(data) { this.contextMenuSource.next(data); } onValueChange(value) { this.valueSource.next(value); } onTotalRecordsChange(value) { this.totalRecordsSource.next(value); } onColumnsChange(columns) { this.columnsSource.next(columns); } } TableService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: TableService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); TableService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: TableService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: TableService, decorators: [{ type: Injectable }] }); class Table { constructor(el, zone, tableService, cd, filterService) { this.el = el; this.zone = zone; this.tableService = tableService; this.cd = cd; this.filterService = filterService; this.pageLinks = 5; this.alwaysShowPaginator = true; this.paginatorPosition = 'bottom'; this.paginatorDropdownScrollHeight = '200px'; this.currentPageReportTemplate = '{currentPage} of {totalPages}'; this.showFirstLastIcon = true; this.showPageLinks = true; this.defaultSortOrder = 1; this.sortMode = 'single'; this.resetPageOnSort = true; this.selectionChange = new EventEmitter(); this.contextMenuSelectionChange = new EventEmitter(); this.contextMenuSelectionMode = "separate"; this.rowTrackBy = (index, item) => item; this.lazy = false; this.lazyLoadOnInit = true; this.compareSelectionBy = 'deepEquals'; this.csvSeparator = ','; this.exportFilename = 'download'; this.filters = {}; this.filterDelay = 300; this.expandedRowKeys = {}; this.editingRowKeys = {}; this.rowExpandMode = 'multiple'; this.virtualScrollDelay = 250; this.virtualRowHeight = 28; this.columnResizeMode = 'fit'; this.loadingIcon = 'pi pi-spinner'; this.showLoader = true; this.showInitialSortBadge = true; this.stateStorage = 'session'; this.editMode = 'cell'; this.onRowSelect = new EventEmitter(); this.onRowUnselect = new EventEmitter(); this.onPage = new EventEmitter(); this.onSort = new EventEmitter(); this.onFilter = new EventEmitter(); this.onLazyLoad = new EventEmitter(); this.onRowExpand = new EventEmitter(); this.onRowCollapse = new EventEmitter(); this.onContextMenuSelect = new EventEmitter(); this.onColResize = new EventEmitter(); this.onColReorder = new EventEmitter(); this.onRowReorder = new EventEmitter(); this.onEditInit = new EventEmitter(); this.onEditComplete = new EventEmitter(); this.onEditCancel = new EventEmitter(); this.onHeaderCheckboxToggle = new EventEmitter(); this.sortFunction = new EventEmitter(); this.firstChange = new EventEmitter(); this.rowsChange = new EventEmitter(); this.onStateSave = new EventEmitter(); this.onStateRestore = new EventEmitter(); this._value = []; this._totalRecords = 0; this._first = 0; this.selectionKeys = {}; this._sortOrder = 1; } ngOnInit() { if (this.lazy && this.lazyLoadOnInit) { if (!this.virtualScroll) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } if (this.restoringFilter) { this.restoringFilter = false; } } this.initialized = true; } ngAfterContentInit() { this.templates.forEach((item) => { switch (item.getType()) { case 'caption': this.captionTemplate = item.template; break; case 'header': this.headerTemplate = item.template; break; case 'body': this.bodyTemplate = item.template; break; case 'loadingbody': this.loadingBodyTemplate = item.template; break; case 'footer': this.footerTemplate = item.template; break; case 'summary': this.summaryTemplate = item.template; break; case 'colgroup': this.colGroupTemplate = item.template; break; case 'rowexpansion': this.expandedRowTemplate = item.template; break; case 'frozenrows': this.frozenRowsTemplate = item.template; break; case 'frozenheader': this.frozenHeaderTemplate = item.template; break; case 'frozenbody': this.frozenBodyTemplate = item.template; break; case 'frozenfooter': this.frozenFooterTemplate = item.template; break; case 'frozencolgroup': this.frozenColGroupTemplate = item.template; break; case 'frozenrowexpansion': this.frozenExpandedRowTemplate = item.template; break; case 'emptymessage': this.emptyMessageTemplate = item.template; break; case 'paginatorleft': this.paginatorLeftTemplate = item.template; break; case 'paginatorright': this.paginatorRightTemplate = item.template; break; case 'paginatordropdownitem': this.paginatorDropdownItemTemplate = item.template; break; } }); } ngAfterViewInit() { if (this.isStateful() && this.resizableColumns) { this.restoreColumnWidths(); } } ngOnChanges(simpleChange) { if (simpleChange.value) { if (this.isStateful() && !this.stateRestored) { this.restoreState(); } this._value = simpleChange.value.currentValue; if (!this.lazy) { this.totalRecords = (this._value ? this._value.length : 0); if (this.sortMode == 'single' && this.sortField) this.sortSingle(); else if (this.sortMode == 'multiple' && this.multiSortMeta) this.sortMultiple(); else if (this.hasFilter()) //sort already filters this._filter(); } this.tableService.onValueChange(simpleChange.value.currentValue); } if (simpleChange.columns) { this._columns = simpleChange.columns.currentValue; this.tableService.onColumnsChange(simpleChange.columns.currentValue); if (this._columns && this.isStateful() && this.reorderableColumns && !this.columnOrderStateRestored) { this.restoreColumnOrder(); } } if (simpleChange.sortField) { this._sortField = simpleChange.sortField.currentValue; //avoid triggering lazy load prior to lazy initialization at onInit if (!this.lazy || this.initialized) { if (this.sortMode === 'single') { this.sortSingle(); } } } if (simpleChange.sortOrder) { this._sortOrder = simpleChange.sortOrder.currentValue; //avoid triggering lazy load prior to lazy initialization at onInit if (!this.lazy || this.initialized) { if (this.sortMode === 'single') { this.sortSingle(); } } } if (simpleChange.multiSortMeta) { this._multiSortMeta = simpleChange.multiSortMeta.currentValue; if (this.sortMode === 'multiple' && (this.initialized || (!this.lazy && !this.virtualScroll))) { this.sortMultiple(); } } if (simpleChange.selection) { this._selection = simpleChange.selection.currentValue; if (!this.preventSelectionSetterPropagation) { this.updateSelectionKeys(); this.tableService.onSelectionChange(); } this.preventSelectionSetterPropagation = false; } } get value() { return this._value; } set value(val) { this._value = val; } get columns() { return this._columns; } set columns(cols) { this._columns = cols; } get first() { return this._first; } set first(val) { this._first = val; } get rows() { return this._rows; } set rows(val) { this._rows = val; } get totalRecords() { return this._totalRecords; } set totalRecords(val) { this._totalRecords = val; this.tableService.onTotalRecordsChange(this._totalRecords); } get sortField() { return this._sortField; } set sortField(val) { this._sortField = val; } get sortOrder() { return this._sortOrder; } set sortOrder(val) { this._sortOrder = val; } get multiSortMeta() { return this._multiSortMeta; } set multiSortMeta(val) { this._multiSortMeta = val; } get selection() { return this._selection; } set selection(val) { this._selection = val; } updateSelectionKeys() { if (this.dataKey && this._selection) { this.selectionKeys = {}; if (Array.isArray(this._selection)) { for (let data of this._selection) { this.selectionKeys[String(ObjectUtils.resolveFieldData(data, this.dataKey))] = 1; } } else { this.selectionKeys[String(ObjectUtils.resolveFieldData(this._selection, this.dataKey))] = 1; } } } onPageChange(event) { this.first = event.first; this.rows = event.rows; if (this.lazy) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } this.onPage.emit({ first: this.first, rows: this.rows }); this.firstChange.emit(this.first); this.rowsChange.emit(this.rows); this.tableService.onValueChange(this.value); if (this.isStateful()) { this.saveState(); } this.anchorRowIndex = null; if (this.scrollable) { this.resetScrollTop(); } } sort(event) { let originalEvent = event.originalEvent; if (this.sortMode === 'single') { this._sortOrder = (this.sortField === event.field) ? this.sortOrder * -1 : this.defaultSortOrder; this._sortField = event.field; if (this.resetPageOnSort) { this._first = 0; this.firstChange.emit(this._first); if (this.scrollable) { this.resetScrollTop(); } } this.sortSingle(); } if (this.sortMode === 'multiple') { let metaKey = originalEvent.metaKey || originalEvent.ctrlKey; let sortMeta = this.getSortMeta(event.field); if (sortMeta) { if (!metaKey) { this._multiSortMeta = [{ field: event.field, order: sortMeta.order * -1 }]; if (this.resetPageOnSort) { this._first = 0; this.firstChange.emit(this._first); if (this.scrollable) { this.resetScrollTop(); } } } else { sortMeta.order = sortMeta.order * -1; } } else { if (!metaKey || !this.multiSortMeta) { this._multiSortMeta = []; if (this.resetPageOnSort) { this._first = 0; this.firstChange.emit(this._first); } } this._multiSortMeta.push({ field: event.field, order: this.defaultSortOrder }); } this.sortMultiple(); } if (this.isStateful()) { this.saveState(); } this.anchorRowIndex = null; } sortSingle() { if (this.sortField && this.sortOrder) { if (this.restoringSort) { this.restoringSort = false; } if (this.lazy) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else if (this.value) { if (this.customSort) { this.sortFunction.emit({ data: this.value, mode: this.sortMode, field: this.sortField, order: this.sortOrder }); } else { this.value.sort((data1, data2) => { let value1 = ObjectUtils.resolveFieldData(data1, this.sortField); let value2 = ObjectUtils.resolveFieldData(data2, this.sortField); let result = null; if (value1 == null && value2 != null) result = -1; else if (value1 != null && value2 == null) result = 1; else if (value1 == null && value2 == null) result = 0; else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2); else result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0; return (this.sortOrder * result); }); this._value = [...this.value]; } if (this.hasFilter()) { this._filter(); } } let sortMeta = { field: this.sortField, order: this.sortOrder }; this.onSort.emit(sortMeta); this.tableService.onSort(sortMeta); } } sortMultiple() { if (this.multiSortMeta) { if (this.lazy) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else if (this.value) { if (this.customSort) { this.sortFunction.emit({ data: this.value, mode: this.sortMode, multiSortMeta: this.multiSortMeta }); } else { this.value.sort((data1, data2) => { return this.multisortField(data1, data2, this.multiSortMeta, 0); }); this._value = [...this.value]; } if (this.hasFilter()) { this._filter(); } } this.onSort.emit({ multisortmeta: this.multiSortMeta }); this.tableService.onSort(this.multiSortMeta); } } multisortField(data1, data2, multiSortMeta, index) { let value1 = ObjectUtils.resolveFieldData(data1, multiSortMeta[index].field); let value2 = ObjectUtils.resolveFieldData(data2, multiSortMeta[index].field); let result = null; if (value1 == null && value2 != null) result = -1; else if (value1 != null && value2 == null) result = 1; else if (value1 == null && value2 == null) result = 0; else if (typeof value1 == 'string' || value1 instanceof String) { if (value1.localeCompare && (value1 != value2)) { return (multiSortMeta[index].order * value1.localeCompare(value2)); } } else { result = (value1 < value2) ? -1 : 1; } if (value1 == value2) { return (multiSortMeta.length - 1) > (index) ? (this.multisortField(data1, data2, multiSortMeta, index + 1)) : 0; } return (multiSortMeta[index].order * result); } getSortMeta(field) { if (this.multiSortMeta && this.multiSortMeta.length) { for (let i = 0; i < this.multiSortMeta.length; i++) { if (this.multiSortMeta[i].field === field) { return this.multiSortMeta[i]; } } } return null; } isSorted(field) { if (this.sortMode === 'single') { return (this.sortField && this.sortField === field); } else if (this.sortMode === 'multiple') { let sorted = false; if (this.multiSortMeta) { for (let i = 0; i < this.multiSortMeta.length; i++) { if (this.multiSortMeta[i].field == field) { sorted = true; break; } } } return sorted; } } handleRowClick(event) { let target = event.originalEvent.target; let targetNode = target.nodeName; let parentNode = target.parentElement && target.parentElement.nodeName; if (targetNode == 'INPUT' || targetNode == 'BUTTON' || targetNode == 'A' || parentNode == 'INPUT' || parentNode == 'BUTTON' || parentNode == 'A' || (DomHandler.hasClass(event.originalEvent.target, 'p-clickable'))) { return; } if (this.selectionMode) { this.preventSelectionSetterPropagation = true; if (this.isMultipleSelectionMode() && event.originalEvent.shiftKey && this.anchorRowIndex != null) { DomHandler.clearSelection(); if (this.rangeRowIndex != null) { this.clearSelectionRange(event.originalEvent); } this.rangeRowIndex = event.rowIndex; this.selectRange(event.originalEvent, event.rowIndex); } else { let rowData = event.rowData; let selected = this.isSelected(rowData); let metaSelection = this.rowTouched ? false : this.metaKeySelection; let dataKeyValue = this.dataKey ? String(ObjectUtils.resolveFieldData(rowData, this.dataKey)) : null; this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; if (metaSelection) { let metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey; if (selected && metaKey) { if (this.isSingleSelectionMode()) { this._selection = null; this.selectionKeys = {}; this.selectionChange.emit(null); } else { let selectionIndex = this.findIndexInSelection(rowData); this._selection = this.selection.filter((val, i) => i != selectionIndex); this.selectionChange.emit(this.selection); if (dataKeyValue) { delete this.selectionKeys[dataKeyValue]; } } this.onRowUnselect.emit({ originalEvent: event.originalEvent, data: rowData, type: 'row' }); } else { if (this.isSingleSelectionMode()) { this._selection = rowData; this.selectionChange.emit(rowData); if (dataKeyValue) { this.selectionKeys = {}; this.selectionKeys[dataKeyValue] = 1; } } else if (this.isMultipleSelectionMode()) { if (metaKey) { this._selection = this.selection || []; } else { this._selection = []; this.selectionKeys = {}; } this._selection = [...this.selection, rowData]; this.selectionChange.emit(this.selection); if (dataKeyValue) { this.selectionKeys[dataKeyValue] = 1; } } this.onRowSelect.emit({ originalEvent: event.originalEvent, data: rowData, type: 'row', index: event.rowIndex }); } } else { if (this.selectionMode === 'single') { if (selected) { this._selection = null; this.selectionKeys = {}; this.selectionChange.emit(this.selection); this.onRowUnselect.emit({ originalEvent: event.originalEvent, data: rowData, type: 'row', index: event.rowIndex }); } else { this._selection = rowData; this.selectionChange.emit(this.selection); this.onRowSelect.emit({ originalEvent: event.originalEvent, data: rowData, type: 'row', index: event.rowIndex }); if (dataKeyValue) { this.selectionKeys = {}; this.selectionKeys[dataKeyValue] = 1; } } } else if (this.selectionMode === 'multiple') { if (selected) { let selectionIndex = this.findIndexInSelection(rowData); this._selection = this.selection.filter((val, i) => i != selectionIndex); this.selectionChange.emit(this.selection); this.onRowUnselect.emit({ originalEvent: event.originalEvent, data: rowData, type: 'row', index: event.rowIndex }); if (dataKeyValue) { delete this.selectionKeys[dataKeyValue]; } } else { this._selection = this.selection ? [...this.selection, rowData] : [rowData]; this.selectionChange.emit(this.selection); this.onRowSelect.emit({ originalEvent: event.originalEvent, data: rowData, type: 'row', index: event.rowIndex }); if (dataKeyValue) { this.selectionKeys[dataKeyValue] = 1; } } } } } this.tableService.onSelectionChange(); if (this.isStateful()) { this.saveState(); } } this.rowTouched = false; } handleRowTouchEnd(event) { this.rowTouched = true; } handleRowRightClick(event) { if (this.contextMenu) { const rowData = event.rowData; if (this.contextMenuSelectionMode === 'separate') { this.contextMenuSelection = rowData; this.contextMenuSelectionChange.emit(rowData); this.onContextMenuSelect.emit({ originalEvent: event.originalEvent, data: rowData, index: event.rowIndex }); this.contextMenu.show(event.originalEvent); this.tableService.onContextMenu(rowData); } else if (this.contextMenuSelectionMode === 'joint') { this.preventSelectionSetterPropagation = true; let selected = this.isSelected(rowData); let dataKeyValue = this.dataKey ? String(ObjectUtils.resolveFieldData(rowData, this.dataKey)) : null; if (!selected) { if (this.isSingleSelectionMode()) { this.selection = rowData; this.selectionChange.emit(rowData); if (dataKeyValue) { this.selectionKeys = {}; this.selectionKeys[dataKeyValue] = 1; } } else if (this.isMultipleSelectionMode()) { this._selection = this.selection ? [...this.selection, rowData] : [rowData]; this.selectionChange.emit(this.selection); if (dataKeyValue) { this.selectionKeys[dataKeyValue] = 1; } } } this.tableService.onSelectionChange(); this.contextMenu.show(event.originalEvent); this.onContextMenuSelect.emit({ originalEvent: event, data: rowData, index: event.rowIndex }); } } } selectRange(event, rowIndex) { let rangeStart, rangeEnd; if (this.anchorRowIndex > rowIndex) { rangeStart = rowIndex; rangeEnd = this.anchorRowIndex; } else if (this.anchorRowIndex < rowIndex) { rangeStart = this.anchorRowIndex; rangeEnd = rowIndex; } else { rangeStart = rowIndex; rangeEnd = rowIndex; } if (this.lazy && this.paginator) { rangeStart -= this.first; rangeEnd -= this.first; } let rangeRowsData = []; for (let i = rangeStart; i <= rangeEnd; i++) { let rangeRowData = this.filteredValue ? this.filteredValue[i] : this.value[i]; if (!this.isSelected(rangeRowData)) { rangeRowsData.push(rangeRowData); this._selection = [...this.selection, rangeRowData]; let dataKeyValue = this.dataKey ? String(ObjectUtils.resolveFieldData(rangeRowData, this.dataKey)) : null; if (dataKeyValue) { this.selectionKeys[dataKeyValue] = 1; } } } this.selectionChange.emit(this.selection); this.onRowSelect.emit({ originalEvent: event, data: rangeRowsData, type: 'row' }); } clearSelectionRange(event) { let rangeStart, rangeEnd; if (this.rangeRowIndex > this.anchorRowIndex) { rangeStart = this.anchorRowIndex; rangeEnd = this.rangeRowIndex; } else if (this.rangeRowIndex < this.anchorRowIndex) { rangeStart = this.rangeRowIndex; rangeEnd = this.anchorRowIndex; } else { rangeStart = this.rangeRowIndex; rangeEnd = this.rangeRowIndex; } for (let i = rangeStart; i <= rangeEnd; i++) { let rangeRowData = this.value[i]; let selectionIndex = this.findIndexInSelection(rangeRowData); this._selection = this.selection.filter((val, i) => i != selectionIndex); let dataKeyValue = this.dataKey ? String(ObjectUtils.resolveFieldData(rangeRowData, this.dataKey)) : null; if (dataKeyValue) { delete this.selectionKeys[dataKeyValue]; } this.onRowUnselect.emit({ originalEvent: event, data: rangeRowData, type: 'row' }); } } isSelected(rowData) { if (rowData && this.selection) { if (this.dataKey) { return this.selectionKeys[ObjectUtils.resolveFieldData(rowData, this.dataKey)] !== undefined; } else { if (this.selection instanceof Array) return this.findIndexInSelection(rowData) > -1; else return this.equals(rowData, this.selection); } } return false; } findIndexInSelection(rowData) { let index = -1; if (this.selection && this.selection.length) { for (let i = 0; i < this.selection.length; i++) { if (this.equals(rowData, this.selection[i])) { index = i; break; } } } return index; } toggleRowWithRadio(event, rowData) { this.preventSelectionSetterPropagation = true; if (this.selection != rowData) { this._selection = rowData; this.selectionChange.emit(this.selection); this.onRowSelect.emit({ originalEvent: event.originalEvent, index: event.rowIndex, data: rowData, type: 'radiobutton' }); if (this.dataKey) { this.selectionKeys = {}; this.selectionKeys[String(ObjectUtils.resolveFieldData(rowData, this.dataKey))] = 1; } } else { this._selection = null; this.selectionChange.emit(this.selection); this.onRowUnselect.emit({ originalEvent: event.originalEvent, index: event.rowIndex, data: rowData, type: 'radiobutton' }); } this.tableService.onSelectionChange(); if (this.isStateful()) { this.saveState(); } } toggleRowWithCheckbox(event, rowData) { this.selection = this.selection || []; let selected = this.isSelected(rowData); let dataKeyValue = this.dataKey ? String(ObjectUtils.resolveFieldData(rowData, this.dataKey)) : null; this.preventSelectionSetterPropagation = true; if (selected) { let selectionIndex = this.findIndexInSelection(rowData); this._selection = this.selection.filter((val, i) => i != selectionIndex); this.selectionChange.emit(this.selection); this.onRowUnselect.emit({ originalEvent: event.originalEvent, index: event.rowIndex, data: rowData, type: 'checkbox' }); if (dataKeyValue) { delete this.selectionKeys[dataKeyValue]; } } else { this._selection = this.selection ? [...this.selection, rowData] : [rowData]; this.selectionChange.emit(this.selection); this.onRowSelect.emit({ originalEvent: event.originalEvent, index: event.rowIndex, data: rowData, type: 'checkbox' }); if (dataKeyValue) { this.selectionKeys[dataKeyValue] = 1; } } this.tableService.onSelectionChange(); if (this.isStateful()) { this.saveState(); } } toggleRowsWithCheckbox(event, check) { this._selection = check ? this.filteredValue ? this.filteredValue.slice() : this.value.slice() : []; this.preventSelectionSetterPropagation = true; this.updateSelectionKeys(); this.selectionChange.emit(this._selection); this.tableService.onSelectionChange(); this.onHeaderCheckboxToggle.emit({ originalEvent: event, checked: check }); if (this.isStateful()) { this.saveState(); } } equals(data1, data2) { return this.compareSelectionBy === 'equals' ? (data1 === data2) : ObjectUtils.equals(data1, data2, this.dataKey); } /* Legacy Filtering for custom elements */ filter(value, field, matchMode) { if (this.filterTimeout) { clearTimeout(this.filterTimeout); } if (!this.isFilterBlank(value)) { this.filters[field] = { value: value, matchMode: matchMode }; } else if (this.filters[field]) { delete this.filters[field]; } this.filterTimeout = setTimeout(() => { this._filter(); this.filterTimeout = null; }, this.filterDelay); this.anchorRowIndex = null; } filterGlobal(value, matchMode) { this.filter(value, 'global', matchMode); } isFilterBlank(filter) { if (filter !== null && filter !== undefined) { if ((typeof filter === 'string' && filter.trim().length == 0) || (filter instanceof Array && filter.length == 0)) return true; else return false; } return true; } _filter() { if (!this.restoringFilter) { this.first = 0; this.firstChange.emit(this.first); } if (this.lazy) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else { if (!this.value) { return; } if (!this.hasFilter()) { this.filteredValue = null; if (this.paginator) { this.totalRecords = this.value ? this.value.length : 0; } } else { let globalFilterFieldsArray; if (this.filters['global']) { if (!this.columns && !this.globalFilterFields) throw new Error('Global filtering requires dynamic columns or globalFilterFields to be defined.'); else globalFilterFieldsArray = this.globalFilterFields || this.columns; } this.filteredValue = []; for (let i = 0; i < this.value.length; i++) { let localMatch = true; let globalMatch = false; let localFiltered = false; for (let prop in this.filters) { if (this.filters.hasOwnProperty(prop) && prop !== 'global') { localFiltered = true; let filterField = prop; let filterMeta = this.filters[filterField]; if (Array.isArray(filterMeta)) { for (let meta of filterMeta) { localMatch = this.executeLocalFilter(filterField, this.value[i], meta); if ((meta.operator === FilterOperator.OR && localMatch) || (meta.operator === FilterOperator.AND && !localMatch)) { break; } } } else { localMatch = this.executeLocalFilter(filterField, this.value[i], filterMeta); } if (!localMatch) { break; } } } if (this.filters['global'] && !globalMatch && globalFilterFieldsArray) { for (let j = 0; j < globalFilterFieldsArray.length; j++) { let globalFilterField = globalFilterFieldsArray[j].field || globalFilterFieldsArray[j]; globalMatch = this.filterService.filters[this.filters['global'].matchMode](ObjectUtils.resolveFieldData(this.value[i], globalFilterField), this.filters['global'].value, this.filterLocale); if (globalMatch) { break; } } } let matches; if (this.filters['global']) { matches = localFiltered ? (localFiltered && localMatch && globalMatch) : globalMatch; } else { matches = localFiltered && localMatch; } if (matches) { this.filteredValue.push(this.value[i]); } } if (this.filteredValue.length === this.value.length) { this.filteredValue = null; } if (this.paginator) { this.totalRecords = this.filteredValue ? this.filteredValue.length : this.value ? this.value.length : 0; } } } this.onFilter.emit({ filters: this.filters, filteredValue: this.filteredValue || this.value }); this.tableService.onValueChange(this.value); if (this.isStateful() && !this.restoringFilter) { this.saveState(); } if (this.restoringFilter) { this.restoringFilter = false; } this.cd.markForCheck(); if (this.scrollable) { this.resetScrollTop(); } } executeLocalFilter(field, rowData, filterMeta) { let filterValue = filterMeta.value; let filterMatchMode = filterMeta.matchMode || FilterMatchMode.STARTS_WITH; let dataFieldValue = ObjectUtils.resolveFieldData(rowData, field); let filterConstraint = this.filterService.filters[filterMatchMode]; return filterConstraint(dataFieldValue, filterValue, this.filterLocale); } hasFilter() { let empty = true; for (let prop in this.filters) { if (this.filters.hasOwnProperty(prop)) { empty = false; break; } } return !empty; } createLazyLoadMetadata() { return { first: this.first, rows: this.rows, sortField: this.sortField, sortOrder: this.sortOrder, filters: this.filters, globalFilter: this.filters && this.filters['global'] ? this.filters['global'].value : null, multiSortMeta: this.multiSortMeta }; } clear() { this._sortField = null; this._sortOrder = this.defaultSortOrder; this._multiSortMeta = null; this.tableService.onSort(null); this.filteredValue = null; this.tableService.onResetChange(); this.first = 0; this.firstChange.emit(this.first); if (this.lazy) { this.onLazyLoad.emit(this.createLazyLoadMetadata()); } else { this.totalRecords = (this._value ? this._value.length : 0); } } reset() { this.clear(); } exportCSV(options) { let data; let csv = ''; let columns = this.frozenColumns ? [...this.frozenColumns, ...this.columns] : this.columns; if (options && options.selectionOnly) { data = this.selection || []; } else { data = this.filteredValue || this.value; if (this.frozenValue) { data = data ? [...this.frozenValue, ...data] : this.frozenValue; } } //headers for (let i = 0; i < columns.length; i++) { let column = columns[i]; if (column.exportable !== false && column.field) { csv += '"' + (column.header || column.field) + '"'; if (i < (columns.length - 1)) { csv += this.csvSeparator; } } } //body data.forEach((record, i) => { csv += '\n'; for (let i = 0; i < columns.length; i++) { let column = columns[i]; if (column.exportable !== false && column.field) { let cellData = ObjectUtils.resolveFieldData(record, column.field); if (cellData != null) { if (this.exportFunction) { cellData = this.exportFunction({ data: cellData, field: column.field }); } else cellData = String(cellData).replace(/"/g, '""'); } else cellData = ''; csv += '"' + cellData + '"'; if (i < (columns.length - 1)) { csv += this.csvSeparator; } } } }); let blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, this.exportFilename + '.csv'); } else { let link = document.createElement("a"); link.style.display = 'none'; document.body.appendChild(link); if (link.download !== undefined) { link.setAttribute('href', URL.createObjectURL(blob)); link.setAttribute('download', this.exportFilename + '.csv'); link.click(); } else { csv = 'data:text/csv;charset=utf-8,' + csv; window.open(encodeURI(csv)); } document.body.removeChild(link); } } resetScrollTop() { if (this.virtualScroll) this.scrollToVirtualIndex(0); else this.scrollTo({ top: 0 }); } scrollToVirtualIndex(index) { if (this.scrollableViewChild) { this.scrollableViewChild.scrollToVirtualIndex(index); } if (this.scrollableFrozenViewChild) { this.scrollableFrozenViewChild.scrollToVirtualIndex(index); } } scrollTo(options) { if (this.scrollableViewChild) { this.scrollableViewChild.scrollTo(options); } if (this.scrollableFrozenViewChild) { this.scrollableFrozenViewChild.scrollTo(options); } } updateEditingCell(cell, data, field, index) { this.editingCell = cell; this.editingCellData = data; this.editingCellField = field; this.editingCellRowIndex = index; this.bindDocumentEditListener(); } isEditingCellValid() { return (this.editingCell && DomHandler.find(this.editingCell, '.ng-invalid.ng-dirty').length === 0); } bindDocumentEditListener() { if (!this.documentEditListener) { this.documentEditListener = (event) => { if (this.editingCell && !this.editingCellClick && this.isEditingCellValid()) { DomHandler.removeClass(this.editingCell, 'p-cell-editing'); this.editingCell = null; this.onEditComplete.emit({ field: this.editingCellField, data: this.editingCellData, originalEvent: event, index: this.editingCellRowIndex }); this.editingCellField = null; this.editingCellData = null; this.editingCellRowIndex = null; this.unbindDocumentEditListener(); this.cd.markForCheck(); } this.editingCellClick = false; }; document.addEventListener('click', this.documentEditListener); } } unbindDocumentEditListener() { if (this.documentEditListener) { document.removeEventListener('click', this.documentEditListener); this.documentEditListener = null; } } initRowEdit(rowData) { let dataKeyValue = String(ObjectUtils.resolveFieldData(rowData, this.dataKey)); this.editingRowKeys[dataKeyValue] = true; } saveRowEdit(rowData, rowElement) { if (DomHandler.find(rowElement, '.ng-invalid.ng-dirty').length === 0) { let dataKeyValue = String(ObjectUtils.resolveFieldData(rowData, this.dataKey)); delete this.editingRowKeys[dataKeyValue]; } } cancelRowEdit(rowData) { let dataKeyValue = String(ObjectUtils.resolveFieldData(rowData, this.dataKey)); delete this.editingRowKeys[dataKeyValue]; } toggleRow(rowData, event) { if (!this.dataKey) { throw new Error('dataKey must be defined to use row expansion'); } let dataKeyValue = String(ObjectUtils.resolveFieldData(rowData, this.dataKey)); if (this.expandedRowKeys[dataKeyValue] != null) { delete this.expandedRowKeys[dataKeyValue]; this.onRowCollapse.emit({ originalEvent: event, data: rowData }); } else { if (this.rowExpandMode === 'single') { this.expandedRowKeys = {}; } this.expandedRowKeys[dataKeyValue] = true; this.onRowExpand.emit({ originalEvent: event, data: rowData }); } if (event) { event.preventDefault(); } if (this.isStateful()) { this.saveState(); } } isRowExpanded(rowData) { return this.expandedRowKeys[String(ObjectUtils.resolveFieldData(rowData, this.dataKey))] === true; } isRowEditing(rowData) { return this.editingRowKeys[String(ObjectUtils.resolveFieldData(rowData, this.dataKey))] === true; } isSingleSelectionMode() { return this.selectionMode === 'single'; } isMultipleSelectionMode() { return this.selectionMode === 'multiple'; } onColumnResizeBegin(event) { let containerLeft = DomHandler.getOffset(this.containerViewChild.nativeElement).left; this.lastResizerHelperX = (event.pageX - containerLeft + this.containerViewChild.nativeElement.scrollLeft); this.onColumnResize(event); event.preventDefault(); } onColumnResize(event) { let containerLeft = DomHandler.getOffset(this.containerViewChild.nativeElement).left; DomHandler.addClass(this.containerViewChild.nativeElement, 'p-unselectable-text'); this.resizeHelperViewChild.nativeElement.style.height = this.containerViewChild.nativeElement.offsetHeight + 'px'; this.resizeHelperViewChild.nativeElement.style.top = 0 + 'px'; this.resizeHelperViewChild.nativeElement.style.left = (event.pageX - containerLeft + this.containerViewChild.nativeElement.scrollLeft) + 'px'; this.resizeHelperViewChild.nativeElement.style.display = 'block'; } onColumnResizeEnd(event, column) { let delta = this.resizeHelperViewChild.nativeElement.offsetLeft - this.lastResizerHelpe