PrimeNG p-table 不支持滚动自动调整(请参阅此处)
我已经设法通过挂钩到 p-table 的状态功能来使滚动、列重新排序、列大小调整和模拟自动调整一起工作。
<p-table
*ngIf="!loading"
[columns]="selectedColumns"
[value]="listRows"
[(selection)]="selectedRows"
[rows]="pageSize"
[totalRecords]="rowCount"
(sortFunction)="sort($event)"
[customSort]="true"
[responsive]="true"
[scrollable]="true"
scrollHeight="550px"
[columnResizeMode]="'expand'"
[reorderableColumns]="true"
[resizableColumns]="true"
stateStorage="local"
[stateKey]="tableStateKey"
>
然后在我的表第一次初始化之前,我检查状态是否存在。如果它不存在,我会计算所有列和行的最长文本宽度,并使用此函数将其保存在表状态存储中
@ViewChild("myCanvas") myCanvas: ElementRef;
.
.
.
getTextLength(text: string) {
const ctx = this.myCanvas.nativeElement.getContext("2d");
ctx.font =
'14px "Univers Next W01 Light", Helvetica, Arial, sans-serif';
return Math.round(ctx.measureText(text).width);
}
这是遍历所有数据的函数
setInitialColumnWidths(columns: any[], rows: any[]) {
// Attempt to guess initial column width if we don't have any stored yet
let tableState = JSON.parse(localStorage.getItem(this.tableStateKey));
if (!tableState) {
tableState = {};
// Add some width for the selection checkbox column
const colWidths = [47];
const colOrder = [];
this.cols.forEach(col => {
let maxStringLength = this.getTextLength(col.header);
maxStringLength = maxStringLength < 100 ? 100 : maxStringLength;
rows.forEach(row => {
if (
col.field &&
row[col.field] &&
this.getTextLength(row[col.field]) > maxStringLength
) {
maxStringLength = this.getTextLength(row[col.field]);
}
});
// Add some extra pixels for padding etc.
colWidths.push(maxStringLength + 50);
colOrder.push(col.field);
});
// The PrimeNG table component state requires the column order to be specified as well
tableState["columnOrder"] = colOrder;
tableState["columnWidths"] = colWidths.join(",");
localStorage.setItem(
this.tableStateKey,
JSON.stringify(tableState)
);
}
}
这比我的效果更好。显然,它不适合其他页面中其余数据中较长的字符串,但它至少设置了 100px 的最小值,并且一旦用户调整了列宽,新的宽度就会存储在本地存储中。