@angular/cdk
Version:
Angular Material Component Development Kit
919 lines • 134 kB
JavaScript
/**
* @license
* Copyright Google LLC 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 { __extends, __read, __spread, __values } from "tslib";
import { Directionality } from '@angular/cdk/bidi';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { isDataSource } from '@angular/cdk/collections';
import { Platform } from '@angular/cdk/platform';
import { DOCUMENT } from '@angular/common';
import { Attribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, Directive, ElementRef, EmbeddedViewRef, Inject, Input, isDevMode, IterableDiffers, Optional, QueryList, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { BehaviorSubject, Observable, of as observableOf, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { CdkColumnDef } from './cell';
import { CdkCellOutlet, CdkFooterRowDef, CdkHeaderRowDef, CdkRowDef } from './row';
import { StickyStyler } from './sticky-styler';
import { getTableDuplicateColumnNameError, getTableMissingMatchingRowDefError, getTableMissingRowDefsError, getTableMultipleDefaultRowDefsError, getTableUnknownColumnError, getTableUnknownDataSourceError } from './table-errors';
/**
* Provides a handle for the table to grab the view container's ng-container to insert data rows.
* @docs-private
*/
var DataRowOutlet = /** @class */ (function () {
function DataRowOutlet(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
DataRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[rowOutlet]' },] }
];
/** @nocollapse */
DataRowOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef },
{ type: ElementRef }
]; };
return DataRowOutlet;
}());
export { DataRowOutlet };
/**
* Provides a handle for the table to grab the view container's ng-container to insert the header.
* @docs-private
*/
var HeaderRowOutlet = /** @class */ (function () {
function HeaderRowOutlet(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
HeaderRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[headerRowOutlet]' },] }
];
/** @nocollapse */
HeaderRowOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef },
{ type: ElementRef }
]; };
return HeaderRowOutlet;
}());
export { HeaderRowOutlet };
/**
* Provides a handle for the table to grab the view container's ng-container to insert the footer.
* @docs-private
*/
var FooterRowOutlet = /** @class */ (function () {
function FooterRowOutlet(viewContainer, elementRef) {
this.viewContainer = viewContainer;
this.elementRef = elementRef;
}
FooterRowOutlet.decorators = [
{ type: Directive, args: [{ selector: '[footerRowOutlet]' },] }
];
/** @nocollapse */
FooterRowOutlet.ctorParameters = function () { return [
{ type: ViewContainerRef },
{ type: ElementRef }
]; };
return FooterRowOutlet;
}());
export { FooterRowOutlet };
/**
* The table template that can be used by the mat-table. Should not be used outside of the
* material library.
* @docs-private
*/
export var CDK_TABLE_TEMPLATE =
// Note that according to MDN, the `caption` element has to be projected as the **first**
// element in the table. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption
"\n <ng-content select=\"caption\"></ng-content>\n <ng-container headerRowOutlet></ng-container>\n <ng-container rowOutlet></ng-container>\n <ng-container footerRowOutlet></ng-container>\n";
/**
* Class used to conveniently type the embedded view ref for rows with a context.
* @docs-private
*/
var RowViewRef = /** @class */ (function (_super) {
__extends(RowViewRef, _super);
function RowViewRef() {
return _super !== null && _super.apply(this, arguments) || this;
}
return RowViewRef;
}(EmbeddedViewRef));
/**
* A data table that can render a header row, data rows, and a footer row.
* Uses the dataSource input to determine the data to be rendered. The data can be provided either
* as a data array, an Observable stream that emits the data array to render, or a DataSource with a
* connect function that will return an Observable stream that emits the data array to render.
*/
var CdkTable = /** @class */ (function () {
function CdkTable(_differs, _changeDetectorRef, _elementRef, role, _dir, _document, _platform) {
this._differs = _differs;
this._changeDetectorRef = _changeDetectorRef;
this._elementRef = _elementRef;
this._dir = _dir;
this._platform = _platform;
/** Subject that emits when the component has been destroyed. */
this._onDestroy = new Subject();
/**
* Map of all the user's defined columns (header, data, and footer cell template) identified by
* name. Collection populated by the column definitions gathered by `ContentChildren` as well as
* any custom column definitions added to `_customColumnDefs`.
*/
this._columnDefsByName = new Map();
/**
* Column definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* column definitions as *its* content child.
*/
this._customColumnDefs = new Set();
/**
* Data row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* built-in data rows as *its* content child.
*/
this._customRowDefs = new Set();
/**
* Header row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has
* built-in header rows as *its* content child.
*/
this._customHeaderRowDefs = new Set();
/**
* Footer row definitions that were defined outside of the direct content children of the table.
* These will be defined when, e.g., creating a wrapper around the cdkTable that has a
* built-in footer row as *its* content child.
*/
this._customFooterRowDefs = new Set();
/**
* Whether the header row definition has been changed. Triggers an update to the header row after
* content is checked. Initialized as true so that the table renders the initial set of rows.
*/
this._headerRowDefChanged = true;
/**
* Whether the footer row definition has been changed. Triggers an update to the footer row after
* content is checked. Initialized as true so that the table renders the initial set of rows.
*/
this._footerRowDefChanged = true;
/**
* Cache of the latest rendered `RenderRow` objects as a map for easy retrieval when constructing
* a new list of `RenderRow` objects for rendering rows. Since the new list is constructed with
* the cached `RenderRow` objects when possible, the row identity is preserved when the data
* and row template matches, which allows the `IterableDiffer` to check rows by reference
* and understand which rows are added/moved/removed.
*
* Implemented as a map of maps where the first key is the `data: T` object and the second is the
* `CdkRowDef<T>` object. With the two keys, the cache points to a `RenderRow<T>` object that
* contains an array of created pairs. The array is necessary to handle cases where the data
* array contains multiple duplicate data objects and each instantiated `RenderRow` must be
* stored.
*/
this._cachedRenderRowsMap = new Map();
/**
* CSS class added to any row or cell that has sticky positioning applied. May be overriden by
* table subclasses.
*/
this.stickyCssClass = 'cdk-table-sticky';
this._multiTemplateDataRows = false;
// TODO(andrewseguin): Remove max value as the end index
// and instead calculate the view on init and scroll.
/**
* Stream containing the latest information on what rows are being displayed on screen.
* Can be used by the data source to as a heuristic of what data should be provided.
*
* @docs-private
*/
this.viewChange = new BehaviorSubject({ start: 0, end: Number.MAX_VALUE });
if (!role) {
this._elementRef.nativeElement.setAttribute('role', 'grid');
}
this._document = _document;
this._isNativeHtmlTable = this._elementRef.nativeElement.nodeName === 'TABLE';
}
Object.defineProperty(CdkTable.prototype, "trackBy", {
/**
* Tracking function that will be used to check the differences in data changes. Used similarly
* to `ngFor` `trackBy` function. Optimize row operations by identifying a row based on its data
* relative to the function to know if a row should be added/removed/moved.
* Accepts a function that takes two parameters, `index` and `item`.
*/
get: function () {
return this._trackByFn;
},
set: function (fn) {
if (isDevMode() && fn != null && typeof fn !== 'function' && console &&
console.warn) {
console.warn("trackBy must be a function, but received " + JSON.stringify(fn) + ".");
}
this._trackByFn = fn;
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTable.prototype, "dataSource", {
/**
* The table's source of data, which can be provided in three ways (in order of complexity):
* - Simple data array (each object represents one table row)
* - Stream that emits a data array each time the array changes
* - `DataSource` object that implements the connect/disconnect interface.
*
* If a data array is provided, the table must be notified when the array's objects are
* added, removed, or moved. This can be done by calling the `renderRows()` function which will
* render the diff since the last table render. If the data array reference is changed, the table
* will automatically trigger an update to the rows.
*
* When providing an Observable stream, the table will trigger an update automatically when the
* stream emits a new array of data.
*
* Finally, when providing a `DataSource` object, the table will use the Observable stream
* provided by the connect function and trigger updates when that stream emits new data array
* values. During the table's ngOnDestroy or when the data source is removed from the table, the
* table will call the DataSource's `disconnect` function (may be useful for cleaning up any
* subscriptions registered during the connect process).
*/
get: function () {
return this._dataSource;
},
set: function (dataSource) {
if (this._dataSource !== dataSource) {
this._switchDataSource(dataSource);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(CdkTable.prototype, "multiTemplateDataRows", {
/**
* Whether to allow multiple rows per data object by evaluating which rows evaluate their 'when'
* predicate to true. If `multiTemplateDataRows` is false, which is the default value, then each
* dataobject will render the first row that evaluates its when predicate to true, in the order
* defined in the table, or otherwise the default row which does not have a when predicate.
*/
get: function () {
return this._multiTemplateDataRows;
},
set: function (v) {
this._multiTemplateDataRows = coerceBooleanProperty(v);
// In Ivy if this value is set via a static attribute (e.g. <table multiTemplateDataRows>),
// this setter will be invoked before the row outlet has been defined hence the null check.
if (this._rowOutlet && this._rowOutlet.viewContainer.length) {
this._forceRenderDataRows();
}
},
enumerable: true,
configurable: true
});
CdkTable.prototype.ngOnInit = function () {
var _this = this;
this._setupStickyStyler();
if (this._isNativeHtmlTable) {
this._applyNativeTableSections();
}
// Set up the trackBy function so that it uses the `RenderRow` as its identity by default. If
// the user has provided a custom trackBy, return the result of that function as evaluated
// with the values of the `RenderRow`'s data and index.
this._dataDiffer = this._differs.find([]).create(function (_i, dataRow) {
return _this.trackBy ? _this.trackBy(dataRow.dataIndex, dataRow.data) : dataRow;
});
};
CdkTable.prototype.ngAfterContentChecked = function () {
// Cache the row and column definitions gathered by ContentChildren and programmatic injection.
this._cacheRowDefs();
this._cacheColumnDefs();
// Make sure that the user has at least added header, footer, or data row def.
if (!this._headerRowDefs.length && !this._footerRowDefs.length && !this._rowDefs.length) {
throw getTableMissingRowDefsError();
}
// Render updates if the list of columns have been changed for the header, row, or footer defs.
this._renderUpdatedColumns();
// If the header row definition has been changed, trigger a render to the header row.
if (this._headerRowDefChanged) {
this._forceRenderHeaderRows();
this._headerRowDefChanged = false;
}
// If the footer row definition has been changed, trigger a render to the footer row.
if (this._footerRowDefChanged) {
this._forceRenderFooterRows();
this._footerRowDefChanged = false;
}
// If there is a data source and row definitions, connect to the data source unless a
// connection has already been made.
if (this.dataSource && this._rowDefs.length > 0 && !this._renderChangeSubscription) {
this._observeRenderChanges();
}
this._checkStickyStates();
};
CdkTable.prototype.ngOnDestroy = function () {
this._rowOutlet.viewContainer.clear();
this._headerRowOutlet.viewContainer.clear();
this._footerRowOutlet.viewContainer.clear();
this._cachedRenderRowsMap.clear();
this._onDestroy.next();
this._onDestroy.complete();
if (isDataSource(this.dataSource)) {
this.dataSource.disconnect(this);
}
};
/**
* Renders rows based on the table's latest set of data, which was either provided directly as an
* input or retrieved through an Observable stream (directly or from a DataSource).
* Checks for differences in the data since the last diff to perform only the necessary
* changes (add/remove/move rows).
*
* If the table's data source is a DataSource or Observable, this will be invoked automatically
* each time the provided Observable stream emits a new data array. Otherwise if your data is
* an array, this function will need to be called to render any changes.
*/
CdkTable.prototype.renderRows = function () {
var _this = this;
this._renderRows = this._getAllRenderRows();
var changes = this._dataDiffer.diff(this._renderRows);
if (!changes) {
return;
}
var viewContainer = this._rowOutlet.viewContainer;
changes.forEachOperation(function (record, prevIndex, currentIndex) {
if (record.previousIndex == null) {
_this._insertRow(record.item, currentIndex);
}
else if (currentIndex == null) {
viewContainer.remove(prevIndex);
}
else {
var view = viewContainer.get(prevIndex);
viewContainer.move(view, currentIndex);
}
});
// Update the meta context of a row's context data (index, count, first, last, ...)
this._updateRowIndexContext();
// Update rows that did not get added/removed/moved but may have had their identity changed,
// e.g. if trackBy matched data on some property but the actual data reference changed.
changes.forEachIdentityChange(function (record) {
var rowView = viewContainer.get(record.currentIndex);
rowView.context.$implicit = record.item.data;
});
this.updateStickyColumnStyles();
};
/**
* Sets the header row definition to be used. Overrides the header row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the header row after the
* table's content is checked.
* @docs-private
* @deprecated Use `addHeaderRowDef` and `removeHeaderRowDef` instead
* @breaking-change 8.0.0
*/
CdkTable.prototype.setHeaderRowDef = function (headerRowDef) {
this._customHeaderRowDefs = new Set([headerRowDef]);
this._headerRowDefChanged = true;
};
/**
* Sets the footer row definition to be used. Overrides the footer row definition gathered by
* using `ContentChild`, if one exists. Sets a flag that will re-render the footer row after the
* table's content is checked.
* @docs-private
* @deprecated Use `addFooterRowDef` and `removeFooterRowDef` instead
* @breaking-change 8.0.0
*/
CdkTable.prototype.setFooterRowDef = function (footerRowDef) {
this._customFooterRowDefs = new Set([footerRowDef]);
this._footerRowDefChanged = true;
};
/** Adds a column definition that was not included as part of the content children. */
CdkTable.prototype.addColumnDef = function (columnDef) {
this._customColumnDefs.add(columnDef);
};
/** Removes a column definition that was not included as part of the content children. */
CdkTable.prototype.removeColumnDef = function (columnDef) {
this._customColumnDefs.delete(columnDef);
};
/** Adds a row definition that was not included as part of the content children. */
CdkTable.prototype.addRowDef = function (rowDef) {
this._customRowDefs.add(rowDef);
};
/** Removes a row definition that was not included as part of the content children. */
CdkTable.prototype.removeRowDef = function (rowDef) {
this._customRowDefs.delete(rowDef);
};
/** Adds a header row definition that was not included as part of the content children. */
CdkTable.prototype.addHeaderRowDef = function (headerRowDef) {
this._customHeaderRowDefs.add(headerRowDef);
this._headerRowDefChanged = true;
};
/** Removes a header row definition that was not included as part of the content children. */
CdkTable.prototype.removeHeaderRowDef = function (headerRowDef) {
this._customHeaderRowDefs.delete(headerRowDef);
this._headerRowDefChanged = true;
};
/** Adds a footer row definition that was not included as part of the content children. */
CdkTable.prototype.addFooterRowDef = function (footerRowDef) {
this._customFooterRowDefs.add(footerRowDef);
this._footerRowDefChanged = true;
};
/** Removes a footer row definition that was not included as part of the content children. */
CdkTable.prototype.removeFooterRowDef = function (footerRowDef) {
this._customFooterRowDefs.delete(footerRowDef);
this._footerRowDefChanged = true;
};
/**
* Updates the header sticky styles. First resets all applied styles with respect to the cells
* sticking to the top. Then, evaluating which cells need to be stuck to the top. This is
* automatically called when the header row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
*/
CdkTable.prototype.updateStickyHeaderRowStyles = function () {
var headerRows = this._getRenderedRows(this._headerRowOutlet);
var tableElement = this._elementRef.nativeElement;
// Hide the thead element if there are no header rows. This is necessary to satisfy
// overzealous a11y checkers that fail because the `rowgroup` element does not contain
// required child `row`.
var thead = tableElement.querySelector('thead');
if (thead) {
thead.style.display = headerRows.length ? '' : 'none';
}
var stickyStates = this._headerRowDefs.map(function (def) { return def.sticky; });
this._stickyStyler.clearStickyPositioning(headerRows, ['top']);
this._stickyStyler.stickRows(headerRows, stickyStates, 'top');
// Reset the dirty state of the sticky input change since it has been used.
this._headerRowDefs.forEach(function (def) { return def.resetStickyChanged(); });
};
/**
* Updates the footer sticky styles. First resets all applied styles with respect to the cells
* sticking to the bottom. Then, evaluating which cells need to be stuck to the bottom. This is
* automatically called when the footer row changes its displayed set of columns, or if its
* sticky input changes. May be called manually for cases where the cell content changes outside
* of these events.
*/
CdkTable.prototype.updateStickyFooterRowStyles = function () {
var footerRows = this._getRenderedRows(this._footerRowOutlet);
var tableElement = this._elementRef.nativeElement;
// Hide the tfoot element if there are no footer rows. This is necessary to satisfy
// overzealous a11y checkers that fail because the `rowgroup` element does not contain
// required child `row`.
var tfoot = tableElement.querySelector('tfoot');
if (tfoot) {
tfoot.style.display = footerRows.length ? '' : 'none';
}
var stickyStates = this._footerRowDefs.map(function (def) { return def.sticky; });
this._stickyStyler.clearStickyPositioning(footerRows, ['bottom']);
this._stickyStyler.stickRows(footerRows, stickyStates, 'bottom');
this._stickyStyler.updateStickyFooterContainer(this._elementRef.nativeElement, stickyStates);
// Reset the dirty state of the sticky input change since it has been used.
this._footerRowDefs.forEach(function (def) { return def.resetStickyChanged(); });
};
/**
* Updates the column sticky styles. First resets all applied styles with respect to the cells
* sticking to the left and right. Then sticky styles are added for the left and right according
* to the column definitions for each cell in each row. This is automatically called when
* the data source provides a new set of data or when a column definition changes its sticky
* input. May be called manually for cases where the cell content changes outside of these events.
*/
CdkTable.prototype.updateStickyColumnStyles = function () {
var _this = this;
var headerRows = this._getRenderedRows(this._headerRowOutlet);
var dataRows = this._getRenderedRows(this._rowOutlet);
var footerRows = this._getRenderedRows(this._footerRowOutlet);
// Clear the left and right positioning from all columns in the table across all rows since
// sticky columns span across all table sections (header, data, footer)
this._stickyStyler.clearStickyPositioning(__spread(headerRows, dataRows, footerRows), ['left', 'right']);
// Update the sticky styles for each header row depending on the def's sticky state
headerRows.forEach(function (headerRow, i) {
_this._addStickyColumnStyles([headerRow], _this._headerRowDefs[i]);
});
// Update the sticky styles for each data row depending on its def's sticky state
this._rowDefs.forEach(function (rowDef) {
// Collect all the rows rendered with this row definition.
var rows = [];
for (var i = 0; i < dataRows.length; i++) {
if (_this._renderRows[i].rowDef === rowDef) {
rows.push(dataRows[i]);
}
}
_this._addStickyColumnStyles(rows, rowDef);
});
// Update the sticky styles for each footer row depending on the def's sticky state
footerRows.forEach(function (footerRow, i) {
_this._addStickyColumnStyles([footerRow], _this._footerRowDefs[i]);
});
// Reset the dirty state of the sticky input change since it has been used.
Array.from(this._columnDefsByName.values()).forEach(function (def) { return def.resetStickyChanged(); });
};
/**
* Get the list of RenderRow objects to render according to the current list of data and defined
* row definitions. If the previous list already contained a particular pair, it should be reused
* so that the differ equates their references.
*/
CdkTable.prototype._getAllRenderRows = function () {
var renderRows = [];
// Store the cache and create a new one. Any re-used RenderRow objects will be moved into the
// new cache while unused ones can be picked up by garbage collection.
var prevCachedRenderRows = this._cachedRenderRowsMap;
this._cachedRenderRowsMap = new Map();
// For each data object, get the list of rows that should be rendered, represented by the
// respective `RenderRow` object which is the pair of `data` and `CdkRowDef`.
for (var i = 0; i < this._data.length; i++) {
var data = this._data[i];
var renderRowsForData = this._getRenderRowsForData(data, i, prevCachedRenderRows.get(data));
if (!this._cachedRenderRowsMap.has(data)) {
this._cachedRenderRowsMap.set(data, new WeakMap());
}
for (var j = 0; j < renderRowsForData.length; j++) {
var renderRow = renderRowsForData[j];
var cache = this._cachedRenderRowsMap.get(renderRow.data);
if (cache.has(renderRow.rowDef)) {
cache.get(renderRow.rowDef).push(renderRow);
}
else {
cache.set(renderRow.rowDef, [renderRow]);
}
renderRows.push(renderRow);
}
}
return renderRows;
};
/**
* Gets a list of `RenderRow<T>` for the provided data object and any `CdkRowDef` objects that
* should be rendered for this data. Reuses the cached RenderRow objects if they match the same
* `(T, CdkRowDef)` pair.
*/
CdkTable.prototype._getRenderRowsForData = function (data, dataIndex, cache) {
var rowDefs = this._getRowDefs(data, dataIndex);
return rowDefs.map(function (rowDef) {
var cachedRenderRows = (cache && cache.has(rowDef)) ? cache.get(rowDef) : [];
if (cachedRenderRows.length) {
var dataRow = cachedRenderRows.shift();
dataRow.dataIndex = dataIndex;
return dataRow;
}
else {
return { data: data, rowDef: rowDef, dataIndex: dataIndex };
}
});
};
/** Update the map containing the content's column definitions. */
CdkTable.prototype._cacheColumnDefs = function () {
var _this = this;
this._columnDefsByName.clear();
var columnDefs = mergeQueryListAndSet(this._contentColumnDefs, this._customColumnDefs);
columnDefs.forEach(function (columnDef) {
if (_this._columnDefsByName.has(columnDef.name)) {
throw getTableDuplicateColumnNameError(columnDef.name);
}
_this._columnDefsByName.set(columnDef.name, columnDef);
});
};
/** Update the list of all available row definitions that can be used. */
CdkTable.prototype._cacheRowDefs = function () {
this._headerRowDefs =
mergeQueryListAndSet(this._contentHeaderRowDefs, this._customHeaderRowDefs);
this._footerRowDefs =
mergeQueryListAndSet(this._contentFooterRowDefs, this._customFooterRowDefs);
this._rowDefs = mergeQueryListAndSet(this._contentRowDefs, this._customRowDefs);
// After all row definitions are determined, find the row definition to be considered default.
var defaultRowDefs = this._rowDefs.filter(function (def) { return !def.when; });
if (!this.multiTemplateDataRows && defaultRowDefs.length > 1) {
throw getTableMultipleDefaultRowDefsError();
}
this._defaultRowDef = defaultRowDefs[0];
};
/**
* Check if the header, data, or footer rows have changed what columns they want to display or
* whether the sticky states have changed for the header or footer. If there is a diff, then
* re-render that section.
*/
CdkTable.prototype._renderUpdatedColumns = function () {
var columnsDiffReducer = function (acc, def) { return acc || !!def.getColumnsDiff(); };
// Force re-render data rows if the list of column definitions have changed.
if (this._rowDefs.reduce(columnsDiffReducer, false)) {
this._forceRenderDataRows();
}
// Force re-render header/footer rows if the list of column definitions have changed..
if (this._headerRowDefs.reduce(columnsDiffReducer, false)) {
this._forceRenderHeaderRows();
}
if (this._footerRowDefs.reduce(columnsDiffReducer, false)) {
this._forceRenderFooterRows();
}
};
/**
* Switch to the provided data source by resetting the data and unsubscribing from the current
* render change subscription if one exists. If the data source is null, interpret this by
* clearing the row outlet. Otherwise start listening for new data.
*/
CdkTable.prototype._switchDataSource = function (dataSource) {
this._data = [];
if (isDataSource(this.dataSource)) {
this.dataSource.disconnect(this);
}
// Stop listening for data from the previous data source.
if (this._renderChangeSubscription) {
this._renderChangeSubscription.unsubscribe();
this._renderChangeSubscription = null;
}
if (!dataSource) {
if (this._dataDiffer) {
this._dataDiffer.diff([]);
}
this._rowOutlet.viewContainer.clear();
}
this._dataSource = dataSource;
};
/** Set up a subscription for the data provided by the data source. */
CdkTable.prototype._observeRenderChanges = function () {
var _this = this;
// If no data source has been set, there is nothing to observe for changes.
if (!this.dataSource) {
return;
}
var dataStream;
if (isDataSource(this.dataSource)) {
dataStream = this.dataSource.connect(this);
}
else if (this.dataSource instanceof Observable) {
dataStream = this.dataSource;
}
else if (Array.isArray(this.dataSource)) {
dataStream = observableOf(this.dataSource);
}
if (dataStream === undefined) {
throw getTableUnknownDataSourceError();
}
this._renderChangeSubscription = dataStream.pipe(takeUntil(this._onDestroy)).subscribe(function (data) {
_this._data = data || [];
_this.renderRows();
});
};
/**
* Clears any existing content in the header row outlet and creates a new embedded view
* in the outlet using the header row definition.
*/
CdkTable.prototype._forceRenderHeaderRows = function () {
var _this = this;
// Clear the header row outlet if any content exists.
if (this._headerRowOutlet.viewContainer.length > 0) {
this._headerRowOutlet.viewContainer.clear();
}
this._headerRowDefs.forEach(function (def, i) { return _this._renderRow(_this._headerRowOutlet, def, i); });
this.updateStickyHeaderRowStyles();
this.updateStickyColumnStyles();
};
/**
* Clears any existing content in the footer row outlet and creates a new embedded view
* in the outlet using the footer row definition.
*/
CdkTable.prototype._forceRenderFooterRows = function () {
var _this = this;
// Clear the footer row outlet if any content exists.
if (this._footerRowOutlet.viewContainer.length > 0) {
this._footerRowOutlet.viewContainer.clear();
}
this._footerRowDefs.forEach(function (def, i) { return _this._renderRow(_this._footerRowOutlet, def, i); });
this.updateStickyFooterRowStyles();
this.updateStickyColumnStyles();
};
/** Adds the sticky column styles for the rows according to the columns' stick states. */
CdkTable.prototype._addStickyColumnStyles = function (rows, rowDef) {
var _this = this;
var columnDefs = Array.from(rowDef.columns || []).map(function (columnName) {
var columnDef = _this._columnDefsByName.get(columnName);
if (!columnDef) {
throw getTableUnknownColumnError(columnName);
}
return columnDef;
});
var stickyStartStates = columnDefs.map(function (columnDef) { return columnDef.sticky; });
var stickyEndStates = columnDefs.map(function (columnDef) { return columnDef.stickyEnd; });
this._stickyStyler.updateStickyColumns(rows, stickyStartStates, stickyEndStates);
};
/** Gets the list of rows that have been rendered in the row outlet. */
CdkTable.prototype._getRenderedRows = function (rowOutlet) {
var renderedRows = [];
for (var i = 0; i < rowOutlet.viewContainer.length; i++) {
var viewRef = rowOutlet.viewContainer.get(i);
renderedRows.push(viewRef.rootNodes[0]);
}
return renderedRows;
};
/**
* Get the matching row definitions that should be used for this row data. If there is only
* one row definition, it is returned. Otherwise, find the row definitions that has a when
* predicate that returns true with the data. If none return true, return the default row
* definition.
*/
CdkTable.prototype._getRowDefs = function (data, dataIndex) {
if (this._rowDefs.length == 1) {
return [this._rowDefs[0]];
}
var rowDefs = [];
if (this.multiTemplateDataRows) {
rowDefs = this._rowDefs.filter(function (def) { return !def.when || def.when(dataIndex, data); });
}
else {
var rowDef = this._rowDefs.find(function (def) { return def.when && def.when(dataIndex, data); }) || this._defaultRowDef;
if (rowDef) {
rowDefs.push(rowDef);
}
}
if (!rowDefs.length) {
throw getTableMissingMatchingRowDefError(data);
}
return rowDefs;
};
/**
* Create the embedded view for the data row template and place it in the correct index location
* within the data row view container.
*/
CdkTable.prototype._insertRow = function (renderRow, renderIndex) {
var rowDef = renderRow.rowDef;
var context = { $implicit: renderRow.data };
this._renderRow(this._rowOutlet, rowDef, renderIndex, context);
};
/**
* Creates a new row template in the outlet and fills it with the set of cell templates.
* Optionally takes a context to provide to the row and cells, as well as an optional index
* of where to place the new row template in the outlet.
*/
CdkTable.prototype._renderRow = function (outlet, rowDef, index, context) {
var e_1, _a;
if (context === void 0) { context = {}; }
// TODO(andrewseguin): enforce that one outlet was instantiated from createEmbeddedView
outlet.viewContainer.createEmbeddedView(rowDef.template, context, index);
try {
for (var _b = __values(this._getCellTemplates(rowDef)), _c = _b.next(); !_c.done; _c = _b.next()) {
var cellTemplate = _c.value;
if (CdkCellOutlet.mostRecentCellOutlet) {
CdkCellOutlet.mostRecentCellOutlet._viewContainer.createEmbeddedView(cellTemplate, context);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
this._changeDetectorRef.markForCheck();
};
/**
* Updates the index-related context for each row to reflect any changes in the index of the rows,
* e.g. first/last/even/odd.
*/
CdkTable.prototype._updateRowIndexContext = function () {
var viewContainer = this._rowOutlet.viewContainer;
for (var renderIndex = 0, count = viewContainer.length; renderIndex < count; renderIndex++) {
var viewRef = viewContainer.get(renderIndex);
var context = viewRef.context;
context.count = count;
context.first = renderIndex === 0;
context.last = renderIndex === count - 1;
context.even = renderIndex % 2 === 0;
context.odd = !context.even;
if (this.multiTemplateDataRows) {
context.dataIndex = this._renderRows[renderIndex].dataIndex;
context.renderIndex = renderIndex;
}
else {
context.index = this._renderRows[renderIndex].dataIndex;
}
}
};
/** Gets the column definitions for the provided row def. */
CdkTable.prototype._getCellTemplates = function (rowDef) {
var _this = this;
if (!rowDef || !rowDef.columns) {
return [];
}
return Array.from(rowDef.columns, function (columnId) {
var column = _this._columnDefsByName.get(columnId);
if (!column) {
throw getTableUnknownColumnError(columnId);
}
return rowDef.extractCellTemplate(column);
});
};
/** Adds native table sections (e.g. tbody) and moves the row outlets into them. */
CdkTable.prototype._applyNativeTableSections = function () {
var e_2, _a;
var documentFragment = this._document.createDocumentFragment();
var sections = [
{ tag: 'thead', outlet: this._headerRowOutlet },
{ tag: 'tbody', outlet: this._rowOutlet },
{ tag: 'tfoot', outlet: this._footerRowOutlet },
];
try {
for (var sections_1 = __values(sections), sections_1_1 = sections_1.next(); !sections_1_1.done; sections_1_1 = sections_1.next()) {
var section = sections_1_1.value;
var element = this._document.createElement(section.tag);
element.setAttribute('role', 'rowgroup');
element.appendChild(section.outlet.elementRef.nativeElement);
documentFragment.appendChild(element);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (sections_1_1 && !sections_1_1.done && (_a = sections_1.return)) _a.call(sections_1);
}
finally { if (e_2) throw e_2.error; }
}
// Use a DocumentFragment so we don't hit the DOM on each iteration.
this._elementRef.nativeElement.appendChild(documentFragment);
};
/**
* Forces a re-render of the data rows. Should be called in cases where there has been an input
* change that affects the evaluation of which rows should be rendered, e.g. toggling
* `multiTemplateDataRows` or adding/removing row definitions.
*/
CdkTable.prototype._forceRenderDataRows = function () {
this._dataDiffer.diff([]);
this._rowOutlet.viewContainer.clear();
this.renderRows();
this.updateStickyColumnStyles();
};
/**
* Checks if there has been a change in sticky states since last check and applies the correct
* sticky styles. Since checking resets the "dirty" state, this should only be performed once
* during a change detection and after the inputs are settled (after content check).
*/
CdkTable.prototype._checkStickyStates = function () {
var stickyCheckReducer = function (acc, d) {
return acc || d.hasStickyChanged();
};
// Note that the check needs to occur for every definition since it notifies the definition
// that it can reset its dirty state. Using another operator like `some` may short-circuit
// remaining definitions and leave them in an unchecked state.
if (this._headerRowDefs.reduce(stickyCheckReducer, false)) {
this.updateStickyHeaderRowStyles();
}
if (this._footerRowDefs.reduce(stickyCheckReducer, false)) {
this.updateStickyFooterRowStyles();
}
if (Array.from(this._columnDefsByName.values()).reduce(stickyCheckReducer, false)) {
this.updateStickyColumnStyles();
}
};
/**
* Creates the sticky styler that will be used for sticky rows and columns. Listens
* for directionality changes and provides the latest direction to the styler. Re-applies column
* stickiness when directionality changes.
*/
CdkTable.prototype._setupStickyStyler = function () {
var _this = this;
var direction = this._dir ? this._dir.value : 'ltr';
this._stickyStyler = new StickyStyler(this._isNativeHtmlTable, this.stickyCssClass, direction, this._platform.isBrowser);
(this._dir ? this._dir.change : observableOf())
.pipe(takeUntil(this._onDestroy))
.subscribe(function (value) {
_this._stickyStyler.direction = value;
_this.updateStickyColumnStyles();
});
};
CdkTable.decorators = [
{ type: Component, args: [{
selector: 'cdk-table, table[cdk-table]',
exportAs: 'cdkTable',
template: CDK_TABLE_TEMPLATE,
host: {
'class': 'cdk-table',
},
encapsulation: ViewEncapsulation.None,
// The "OnPush" status for the `MatTable` component is effectively a noop, so we are removing it.
// The view for `MatTable` consists entirely of templates declared in other views. As they are
// declared elsewhere, they are checked when their declaration points are checked.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default
}] }
];
/** @nocollapse */
CdkTable.ctorParameters = function () { return [
{ type: IterableDiffers },
{ type: ChangeDetectorRef },
{ type: ElementRef },
{ type: String, decorators: [{ type: Attribute, args: ['role',] }] },
{ type: Directionality, decorators: [{ type: Optional }] },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
{ type: Platform }
]; };
CdkTable.propDecorators = {
trackBy: [{ type: Input }],
dataSource: [{ type: Input }],
multiTemplateDataRows: [{ type: Input }],
_rowOutlet: [{ type: ViewChild, args: [DataRowOutlet, { static: true },] }],
_headerRowOutlet: [{ type: ViewChild, args: [HeaderRowOutlet, { static: true },] }],
_footerRowOutlet: [{ type: ViewChild, args: [FooterRowOutlet, { static: true },] }],
_contentColumnDefs: [{ type: ContentChildren, args: [CdkColumnDef, { descendants: true },] }],
_contentRowDefs: [{ type: ContentChildren, args: [CdkRowDef, { descendants: true },] }],
_contentHeaderRowDefs: [{ type: ContentChildren, args: [CdkHeaderRowDef, {
descendants: true
},] }],
_contentFooterRowDefs: [{ type: ContentChildren, args: [CdkFooterRowDef, {
descendants: true
},] }]
};
return CdkTable;
}());
export { CdkTable };
/** Utility function that gets a merged list of the entries in a QueryList and values of a Set. */
function mergeQueryListAndSet(queryList, set) {
return queryList.toArray().concat(Array.from(set));
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid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