-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
table.ts
1475 lines (1283 loc) · 52.9 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
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @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.dev/license
*/
import {Direction, Directionality} from '@angular/cdk/bidi';
import {
CollectionViewer,
DataSource,
_DisposeViewRepeaterStrategy,
_RecycleViewRepeaterStrategy,
isDataSource,
_VIEW_REPEATER_STRATEGY,
_ViewRepeater,
_ViewRepeaterItemChange,
_ViewRepeaterItemInsertArgs,
_ViewRepeaterOperation,
} from '@angular/cdk/collections';
import {Platform} from '@angular/cdk/platform';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {DOCUMENT} from '@angular/common';
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
Directive,
ElementRef,
EmbeddedViewRef,
EventEmitter,
Input,
IterableChangeRecord,
IterableDiffer,
IterableDiffers,
OnDestroy,
OnInit,
Output,
QueryList,
TemplateRef,
TrackByFunction,
ViewContainerRef,
ViewEncapsulation,
booleanAttribute,
inject,
afterNextRender,
Injector,
HostAttributeToken,
} from '@angular/core';
import {
BehaviorSubject,
isObservable,
Observable,
of as observableOf,
Subject,
Subscription,
} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {CdkColumnDef} from './cell';
import {_CoalescedStyleScheduler, _COALESCED_STYLE_SCHEDULER} from './coalesced-style-scheduler';
import {
BaseRowDef,
CdkCellOutlet,
CdkCellOutletMultiRowContext,
CdkCellOutletRowContext,
CdkFooterRowDef,
CdkHeaderRowDef,
CdkNoDataRow,
CdkRowDef,
} from './row';
import {StickyStyler} from './sticky-styler';
import {
getTableDuplicateColumnNameError,
getTableMissingMatchingRowDefError,
getTableMissingRowDefsError,
getTableMultipleDefaultRowDefsError,
getTableUnknownColumnError,
getTableUnknownDataSourceError,
} from './table-errors';
import {STICKY_POSITIONING_LISTENER, StickyPositioningListener} from './sticky-position-listener';
import {CDK_TABLE} from './tokens';
/**
* Enables the recycle view repeater strategy, which reduces rendering latency. Not compatible with
* tables that animate rows.
*/
@Directive({
selector: 'cdk-table[recycleRows], table[cdk-table][recycleRows]',
providers: [{provide: _VIEW_REPEATER_STRATEGY, useClass: _RecycleViewRepeaterStrategy}],
})
export class CdkRecycleRows {}
/** Interface used to provide an outlet for rows to be inserted into. */
export interface RowOutlet {
viewContainer: ViewContainerRef;
}
/** Possible types that can be set as the data source for a `CdkTable`. */
export type CdkTableDataSourceInput<T> = readonly T[] | DataSource<T> | Observable<readonly T[]>;
/**
* Provides a handle for the table to grab the view container's ng-container to insert data rows.
* @docs-private
*/
@Directive({
selector: '[rowOutlet]',
})
export class DataRowOutlet implements RowOutlet {
viewContainer = inject(ViewContainerRef);
elementRef = inject(ElementRef);
constructor(...args: unknown[]);
constructor() {
const table = inject<CdkTable<unknown>>(CDK_TABLE);
table._rowOutlet = this;
table._outletAssigned();
}
}
/**
* Provides a handle for the table to grab the view container's ng-container to insert the header.
* @docs-private
*/
@Directive({
selector: '[headerRowOutlet]',
})
export class HeaderRowOutlet implements RowOutlet {
viewContainer = inject(ViewContainerRef);
elementRef = inject(ElementRef);
constructor(...args: unknown[]);
constructor() {
const table = inject<CdkTable<unknown>>(CDK_TABLE);
table._headerRowOutlet = this;
table._outletAssigned();
}
}
/**
* Provides a handle for the table to grab the view container's ng-container to insert the footer.
* @docs-private
*/
@Directive({
selector: '[footerRowOutlet]',
})
export class FooterRowOutlet implements RowOutlet {
viewContainer = inject(ViewContainerRef);
elementRef = inject(ElementRef);
constructor(...args: unknown[]);
constructor() {
const table = inject<CdkTable<unknown>>(CDK_TABLE);
table._footerRowOutlet = this;
table._outletAssigned();
}
}
/**
* Provides a handle for the table to grab the view
* container's ng-container to insert the no data row.
* @docs-private
*/
@Directive({
selector: '[noDataRowOutlet]',
})
export class NoDataRowOutlet implements RowOutlet {
viewContainer = inject(ViewContainerRef);
elementRef = inject(ElementRef);
constructor(...args: unknown[]);
constructor() {
const table = inject<CdkTable<unknown>>(CDK_TABLE);
table._noDataRowOutlet = this;
table._outletAssigned();
}
}
/**
* The table template that can be used by the mat-table. Should not be used outside of the
* material library.
* @docs-private
*/
export const 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
`
<ng-content select="caption"/>
<ng-content select="colgroup, col"/>
<!--
Unprojected content throws a hydration error so we need this to capture it.
It gets removed on the client so it doesn't affect the layout.
-->
@if (_isServer) {
<ng-content/>
}
@if (_isNativeHtmlTable) {
<thead role="rowgroup">
<ng-container headerRowOutlet/>
</thead>
<tbody role="rowgroup">
<ng-container rowOutlet/>
<ng-container noDataRowOutlet/>
</tbody>
<tfoot role="rowgroup">
<ng-container footerRowOutlet/>
</tfoot>
} @else {
<ng-container headerRowOutlet/>
<ng-container rowOutlet/>
<ng-container noDataRowOutlet/>
<ng-container footerRowOutlet/>
}
`;
/**
* Interface used to conveniently type the possible context interfaces for the render row.
* @docs-private
*/
export interface RowContext<T>
extends CdkCellOutletMultiRowContext<T>,
CdkCellOutletRowContext<T> {}
/**
* Class used to conveniently type the embedded view ref for rows with a context.
* @docs-private
*/
abstract class RowViewRef<T> extends EmbeddedViewRef<RowContext<T>> {}
/**
* Set of properties that represents the identity of a single rendered row.
*
* When the table needs to determine the list of rows to render, it will do so by iterating through
* each data object and evaluating its list of row templates to display (when multiTemplateDataRows
* is false, there is only one template per data object). For each pair of data object and row
* template, a `RenderRow` is added to the list of rows to render. If the data object and row
* template pair has already been rendered, the previously used `RenderRow` is added; else a new
* `RenderRow` is * created. Once the list is complete and all data objects have been iterated
* through, a diff is performed to determine the changes that need to be made to the rendered rows.
*
* @docs-private
*/
export interface RenderRow<T> {
data: T;
dataIndex: number;
rowDef: CdkRowDef<T>;
}
/**
* 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.
*/
@Component({
selector: 'cdk-table, table[cdk-table]',
exportAs: 'cdkTable',
template: CDK_TABLE_TEMPLATE,
styleUrl: 'table.css',
host: {
'class': 'cdk-table',
'[class.cdk-table-fixed-layout]': 'fixedLayout',
},
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,
providers: [
{provide: CDK_TABLE, useExisting: CdkTable},
{provide: _VIEW_REPEATER_STRATEGY, useClass: _DisposeViewRepeaterStrategy},
{provide: _COALESCED_STYLE_SCHEDULER, useClass: _CoalescedStyleScheduler},
// Prevent nested tables from seeing this table's StickyPositioningListener.
{provide: STICKY_POSITIONING_LISTENER, useValue: null},
],
imports: [HeaderRowOutlet, DataRowOutlet, NoDataRowOutlet, FooterRowOutlet],
})
export class CdkTable<T>
implements AfterContentInit, AfterContentChecked, CollectionViewer, OnDestroy, OnInit
{
protected readonly _differs = inject(IterableDiffers);
protected readonly _changeDetectorRef = inject(ChangeDetectorRef);
protected readonly _elementRef = inject(ElementRef);
protected readonly _dir = inject(Directionality, {optional: true});
private _platform = inject(Platform);
protected readonly _viewRepeater =
inject<_ViewRepeater<T, RenderRow<T>, RowContext<T>>>(_VIEW_REPEATER_STRATEGY);
protected readonly _coalescedStyleScheduler = inject<_CoalescedStyleScheduler>(
_COALESCED_STYLE_SCHEDULER,
);
private readonly _viewportRuler = inject(ViewportRuler);
protected readonly _stickyPositioningListener = inject<StickyPositioningListener>(
STICKY_POSITIONING_LISTENER,
{optional: true, skipSelf: true},
)!;
private _document = inject(DOCUMENT);
/** Latest data provided by the data source. */
protected _data: readonly T[];
/** Subject that emits when the component has been destroyed. */
private readonly _onDestroy = new Subject<void>();
/** List of the rendered rows as identified by their `RenderRow` object. */
private _renderRows: RenderRow<T>[];
/** Subscription that listens for the data provided by the data source. */
private _renderChangeSubscription: Subscription | null;
/**
* 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`.
*/
private _columnDefsByName = new Map<string, CdkColumnDef>();
/**
* Set of all row definitions that can be used by this table. Populated by the rows gathered by
* using `ContentChildren` as well as any custom row definitions added to `_customRowDefs`.
*/
private _rowDefs: CdkRowDef<T>[];
/**
* Set of all header row definitions that can be used by this table. Populated by the rows
* gathered by using `ContentChildren` as well as any custom row definitions added to
* `_customHeaderRowDefs`.
*/
private _headerRowDefs: CdkHeaderRowDef[];
/**
* Set of all row definitions that can be used by this table. Populated by the rows gathered by
* using `ContentChildren` as well as any custom row definitions added to
* `_customFooterRowDefs`.
*/
private _footerRowDefs: CdkFooterRowDef[];
/** Differ used to find the changes in the data provided by the data source. */
private _dataDiffer: IterableDiffer<RenderRow<T>>;
/** Stores the row definition that does not have a when predicate. */
private _defaultRowDef: CdkRowDef<T> | null;
/**
* 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.
*/
private _customColumnDefs = new Set<CdkColumnDef>();
/**
* 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.
*/
private _customRowDefs = new Set<CdkRowDef<T>>();
/**
* 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.
*/
private _customHeaderRowDefs = new Set<CdkHeaderRowDef>();
/**
* 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.
*/
private _customFooterRowDefs = new Set<CdkFooterRowDef>();
/** No data row that was defined outside of the direct content children of the table. */
private _customNoDataRow: CdkNoDataRow | null;
/**
* 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.
*/
private _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.
*/
private _footerRowDefChanged = true;
/**
* Whether the sticky column styles need to be updated. Set to `true` when the visible columns
* change.
*/
private _stickyColumnStylesNeedReset = true;
/**
* Whether the sticky styler should recalculate cell widths when applying sticky styles. If
* `false`, cached values will be used instead. This is only applicable to tables with
* {@link fixedLayout} enabled. For other tables, cell widths will always be recalculated.
*/
private _forceRecalculateCellWidths = 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.
*/
private _cachedRenderRowsMap = new Map<T, WeakMap<CdkRowDef<T>, RenderRow<T>[]>>();
/** Whether the table is applied to a native `<table>`. */
protected _isNativeHtmlTable: boolean;
/**
* Utility class that is responsible for applying the appropriate sticky positioning styles to
* the table's rows and cells.
*/
private _stickyStyler: StickyStyler;
/**
* CSS class added to any row or cell that has sticky positioning applied. May be overridden by
* table subclasses.
*/
protected stickyCssClass: string = 'cdk-table-sticky';
/**
* Whether to manually add position: sticky to all sticky cell elements. Not needed if
* the position is set in a selector associated with the value of stickyCssClass. May be
* overridden by table subclasses
*/
protected needsPositionStickyOnElement = true;
/** Whether the component is being rendered on the server. */
protected _isServer: boolean;
/** Whether the no data row is currently showing anything. */
private _isShowingNoDataRow = false;
/** Whether the table has rendered out all the outlets for the first time. */
private _hasAllOutlets = false;
/** Whether the table is done initializing. */
private _hasInitialized = false;
/** Aria role to apply to the table's cells based on the table's own role. */
_getCellRole(): string | null {
// Perform this lazily in case the table's role was updated by a directive after construction.
if (this._cellRoleInternal === undefined) {
// Note that we set `role="cell"` even on native `td` elements,
// because some browsers seem to require it. See #29784.
const tableRole = this._elementRef.nativeElement.getAttribute('role');
return tableRole === 'grid' || tableRole === 'treegrid' ? 'gridcell' : 'cell';
}
return this._cellRoleInternal;
}
private _cellRoleInternal: string | null | undefined = undefined;
/**
* 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`.
*/
@Input()
get trackBy(): TrackByFunction<T> {
return this._trackByFn;
}
set trackBy(fn: TrackByFunction<T>) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {
console.warn(`trackBy must be a function, but received ${JSON.stringify(fn)}.`);
}
this._trackByFn = fn;
}
private _trackByFn: TrackByFunction<T>;
/**
* 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).
*/
@Input()
get dataSource(): CdkTableDataSourceInput<T> {
return this._dataSource;
}
set dataSource(dataSource: CdkTableDataSourceInput<T>) {
if (this._dataSource !== dataSource) {
this._switchDataSource(dataSource);
}
}
private _dataSource: CdkTableDataSourceInput<T>;
/**
* 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.
*/
@Input({transform: booleanAttribute})
get multiTemplateDataRows(): boolean {
return this._multiTemplateDataRows;
}
set multiTemplateDataRows(value: boolean) {
this._multiTemplateDataRows = value;
// 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();
this.updateStickyColumnStyles();
}
}
_multiTemplateDataRows: boolean = false;
/**
* Whether to use a fixed table layout. Enabling this option will enforce consistent column widths
* and optimize rendering sticky styles for native tables. No-op for flex tables.
*/
@Input({transform: booleanAttribute})
get fixedLayout(): boolean {
return this._fixedLayout;
}
set fixedLayout(value: boolean) {
this._fixedLayout = value;
// Toggling `fixedLayout` may change column widths. Sticky column styles should be recalculated.
this._forceRecalculateCellWidths = true;
this._stickyColumnStylesNeedReset = true;
}
private _fixedLayout: boolean = false;
/**
* Emits when the table completes rendering a set of data rows based on the latest data from the
* data source, even if the set of rows is empty.
*/
@Output()
readonly contentChanged = new EventEmitter<void>();
// 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
*/
readonly viewChange = new BehaviorSubject<{start: number; end: number}>({
start: 0,
end: Number.MAX_VALUE,
});
// Outlets in the table's template where the header, data rows, and footer will be inserted.
_rowOutlet: DataRowOutlet;
_headerRowOutlet: HeaderRowOutlet;
_footerRowOutlet: FooterRowOutlet;
_noDataRowOutlet: NoDataRowOutlet;
/**
* The column definitions provided by the user that contain what the header, data, and footer
* cells should render for each column.
*/
@ContentChildren(CdkColumnDef, {descendants: true}) _contentColumnDefs: QueryList<CdkColumnDef>;
/** Set of data row definitions that were provided to the table as content children. */
@ContentChildren(CdkRowDef, {descendants: true}) _contentRowDefs: QueryList<CdkRowDef<T>>;
/** Set of header row definitions that were provided to the table as content children. */
@ContentChildren(CdkHeaderRowDef, {
descendants: true,
})
_contentHeaderRowDefs: QueryList<CdkHeaderRowDef>;
/** Set of footer row definitions that were provided to the table as content children. */
@ContentChildren(CdkFooterRowDef, {
descendants: true,
})
_contentFooterRowDefs: QueryList<CdkFooterRowDef>;
/** Row definition that will only be rendered if there's no data in the table. */
@ContentChild(CdkNoDataRow) _noDataRow: CdkNoDataRow;
private _injector = inject(Injector);
constructor(...args: unknown[]);
constructor() {
const role = inject(new HostAttributeToken('role'), {optional: true});
if (!role) {
this._elementRef.nativeElement.setAttribute('role', 'table');
}
this._isServer = !this._platform.isBrowser;
this._isNativeHtmlTable = this._elementRef.nativeElement.nodeName === 'TABLE';
}
ngOnInit() {
this._setupStickyStyler();
// 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((_i: number, dataRow: RenderRow<T>) => {
return this.trackBy ? this.trackBy(dataRow.dataIndex, dataRow.data) : dataRow;
});
this._viewportRuler
.change()
.pipe(takeUntil(this._onDestroy))
.subscribe(() => {
this._forceRecalculateCellWidths = true;
});
}
ngAfterContentInit() {
this._hasInitialized = true;
}
ngAfterContentChecked() {
// Only start re-rendering in `ngAfterContentChecked` after the first render.
if (this._canRender()) {
this._render();
}
}
ngOnDestroy() {
[
this._rowOutlet?.viewContainer,
this._headerRowOutlet?.viewContainer,
this._footerRowOutlet?.viewContainer,
this._cachedRenderRowsMap,
this._customColumnDefs,
this._customRowDefs,
this._customHeaderRowDefs,
this._customFooterRowDefs,
this._columnDefsByName,
].forEach((def: ViewContainerRef | Set<unknown> | Map<unknown, unknown> | undefined) => {
def?.clear();
});
this._headerRowDefs = [];
this._footerRowDefs = [];
this._defaultRowDef = null;
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.
*/
renderRows() {
this._renderRows = this._getAllRenderRows();
const changes = this._dataDiffer.diff(this._renderRows);
if (!changes) {
this._updateNoDataRow();
this.contentChanged.next();
return;
}
const viewContainer = this._rowOutlet.viewContainer;
this._viewRepeater.applyChanges(
changes,
viewContainer,
(
record: IterableChangeRecord<RenderRow<T>>,
_adjustedPreviousIndex: number | null,
currentIndex: number | null,
) => this._getEmbeddedViewArgs(record.item, currentIndex!),
record => record.item.data,
(change: _ViewRepeaterItemChange<RenderRow<T>, RowContext<T>>) => {
if (change.operation === _ViewRepeaterOperation.INSERTED && change.context) {
this._renderCellTemplateForItem(change.record.item.rowDef, change.context);
}
},
);
// 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((record: IterableChangeRecord<RenderRow<T>>) => {
const rowView = <RowViewRef<T>>viewContainer.get(record.currentIndex!);
rowView.context.$implicit = record.item.data;
});
this._updateNoDataRow();
afterNextRender(
() => {
this.updateStickyColumnStyles();
},
{injector: this._injector},
);
this.contentChanged.next();
}
/** Adds a column definition that was not included as part of the content children. */
addColumnDef(columnDef: CdkColumnDef) {
this._customColumnDefs.add(columnDef);
}
/** Removes a column definition that was not included as part of the content children. */
removeColumnDef(columnDef: CdkColumnDef) {
this._customColumnDefs.delete(columnDef);
}
/** Adds a row definition that was not included as part of the content children. */
addRowDef(rowDef: CdkRowDef<T>) {
this._customRowDefs.add(rowDef);
}
/** Removes a row definition that was not included as part of the content children. */
removeRowDef(rowDef: CdkRowDef<T>) {
this._customRowDefs.delete(rowDef);
}
/** Adds a header row definition that was not included as part of the content children. */
addHeaderRowDef(headerRowDef: CdkHeaderRowDef) {
this._customHeaderRowDefs.add(headerRowDef);
this._headerRowDefChanged = true;
}
/** Removes a header row definition that was not included as part of the content children. */
removeHeaderRowDef(headerRowDef: CdkHeaderRowDef) {
this._customHeaderRowDefs.delete(headerRowDef);
this._headerRowDefChanged = true;
}
/** Adds a footer row definition that was not included as part of the content children. */
addFooterRowDef(footerRowDef: CdkFooterRowDef) {
this._customFooterRowDefs.add(footerRowDef);
this._footerRowDefChanged = true;
}
/** Removes a footer row definition that was not included as part of the content children. */
removeFooterRowDef(footerRowDef: CdkFooterRowDef) {
this._customFooterRowDefs.delete(footerRowDef);
this._footerRowDefChanged = true;
}
/** Sets a no data row definition that was not included as a part of the content children. */
setNoDataRow(noDataRow: CdkNoDataRow | null) {
this._customNoDataRow = noDataRow;
}
/**
* 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.
*/
updateStickyHeaderRowStyles(): void {
const headerRows = this._getRenderedRows(this._headerRowOutlet);
// 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`.
if (this._isNativeHtmlTable) {
const thead = closestTableSection(this._headerRowOutlet, 'thead');
if (thead) {
thead.style.display = headerRows.length ? '' : 'none';
}
}
const stickyStates = this._headerRowDefs.map(def => 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(def => 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.
*/
updateStickyFooterRowStyles(): void {
const footerRows = this._getRenderedRows(this._footerRowOutlet);
// 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`.
if (this._isNativeHtmlTable) {
const tfoot = closestTableSection(this._footerRowOutlet, 'tfoot');
if (tfoot) {
tfoot.style.display = footerRows.length ? '' : 'none';
}
}
const stickyStates = this._footerRowDefs.map(def => 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(def => 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.
*/
updateStickyColumnStyles() {
const headerRows = this._getRenderedRows(this._headerRowOutlet);
const dataRows = this._getRenderedRows(this._rowOutlet);
const footerRows = this._getRenderedRows(this._footerRowOutlet);
// For tables not using a fixed layout, the column widths may change when new rows are rendered.
// In a table using a fixed layout, row content won't affect column width, so sticky styles
// don't need to be cleared unless either the sticky column config changes or one of the row
// defs change.
if ((this._isNativeHtmlTable && !this._fixedLayout) || this._stickyColumnStylesNeedReset) {
// 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(
[...headerRows, ...dataRows, ...footerRows],
['left', 'right'],
);
this._stickyColumnStylesNeedReset = false;
}
// Update the sticky styles for each header row depending on the def's sticky state
headerRows.forEach((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(rowDef => {
// Collect all the rows rendered with this row definition.
const rows: HTMLElement[] = [];
for (let 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((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(def => def.resetStickyChanged());
}
/** Invoked whenever an outlet is created and has been assigned to the table. */
_outletAssigned(): void {
// Trigger the first render once all outlets have been assigned. We do it this way, as
// opposed to waiting for the next `ngAfterContentChecked`, because we don't know when
// the next change detection will happen.
// Also we can't use queries to resolve the outlets, because they're wrapped in a
// conditional, so we have to rely on them being assigned via DI.
if (
!this._hasAllOutlets &&
this._rowOutlet &&
this._headerRowOutlet &&
this._footerRowOutlet &&
this._noDataRowOutlet
) {
this._hasAllOutlets = true;
// In some setups this may fire before `ngAfterContentInit`
// so we need a check here. See #28538.
if (this._canRender()) {
this._render();
}
}
}
/** Whether the table has all the information to start rendering. */
private _canRender(): boolean {
return this._hasAllOutlets && this._hasInitialized;
}
/** Renders the table if its state has changed. */
private _render(): void {
// 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 &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throw getTableMissingRowDefsError();
}
// Render updates if the list of columns have been changed for the header, row, or footer defs.
const columnsChanged = this._renderUpdatedColumns();
const rowDefsChanged = columnsChanged || this._headerRowDefChanged || this._footerRowDefChanged;
// Ensure sticky column styles are reset if set to `true` elsewhere.
this._stickyColumnStylesNeedReset = this._stickyColumnStylesNeedReset || rowDefsChanged;
this._forceRecalculateCellWidths = rowDefsChanged;
// 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();
} else if (this._stickyColumnStylesNeedReset) {
// In the above case, _observeRenderChanges will result in updateStickyColumnStyles being
// called when it row data arrives. Otherwise, we need to call it proactively.
this.updateStickyColumnStyles();
}
this._checkStickyStates();
}
/**
* 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.
*/
private _getAllRenderRows(): RenderRow<T>[] {
const renderRows: RenderRow<T>[] = [];
// 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.
const 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 (let i = 0; i < this._data.length; i++) {
let data = this._data[i];
const renderRowsForData = this._getRenderRowsForData(data, i, prevCachedRenderRows.get(data));
if (!this._cachedRenderRowsMap.has(data)) {
this._cachedRenderRowsMap.set(data, new WeakMap());
}
for (let j = 0; j < renderRowsForData.length; j++) {
let renderRow = renderRowsForData[j];