数据表:绑定列宽

Datatable: bind column width

如何为 PrimeNG 数据绑定列宽 table?

这都行不通:

<p-dataTable [value]="rows">
    <p-column *ngFor="let col of cols2" [field]="col.FieldName" [header]="col.Caption" [style.width.px]="col.Width" >

也不是这个:

<p-dataTable [value]="rows" >
    <p-column *ngFor="let col of cols2" [field]="col.FieldName" [header]="col.Caption" [style]="col.Style" >

列宽不能这样定义:

[style]="{width: '180px', 'text-align': 'center'}" 

因为它是动态的。

这应该有效:

[tableStyle]="{width: '180px','text-align':'center'}" 

注意 text-align 需要 'text-align' 而不是 text-align

<p-dataTable  [tableStyle]="{width: '180px','text-align':'center'}"  >
  <p-column *ngFor="let col of cols2" [field]="col.fieldName" 
         [header]="col.Caption">
  </p-column>
</p-dataTable>

这是一个有效的 Plunker

您可以像这样设置 table 宽度

<p-dataTable [value]="cars" [rows]="10" [paginator]="true" [pageLinks]="3" [responsive]="true" [stacked]="stacked" [style]="{'width': '500px'}">
    <p-header>Responsive</p-header>
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

如果您知道您将拥有多少列,那么您可以根据它进行排列,例如如果您需要 180 像素的两列,然后将 table 宽度设置为 360 像素,您将有两个相同的列,它们的宽度为 180 像素宽度。

构建列时,将 Style 设置为一个对象。这对我有用:

cols2: ColumnSettings[] = [
    {
        FieldName: 'Name',
        Caption: 'Caption',
        Style: { 'width': '180px', 'text-align': 'center' }
    },
    ....
];

可变列宽
使用以下解决方案设置单独的列宽:

<p-column field="vin" header="Vin" [style]="{'width': someColWidthVariable }"></p-column>

您也可以指定为 [style]="{'width':'22px'}"[style]="{'width':'20%'}" 或绑定到某个变量。一个例子是

<p-dataTable>
  <p-column *ngFor="let col of cols2" [field]="col.fieldName" 
         [header]="col.Caption" [style]="{'width': col.width }">
  </p-column>
</p-dataTable>

自动调整列
如果您想要自动调整列以便根据内容自动调整宽度,请将 table-layout 设置为 auto。 primeng中默认为'fixed',即列宽均匀分布

例如

<p-dataTable [tableStyle]="{'table-layout':'auto'}" class="composite-table" [(value)]="model.calcLines"

在 .ts 文件中指定样式,如下所示 "Style" this.cols = [ { field: 'tableName', header: 'Table Name', Style: {width: '180px', 'text-align': 'center'}, sort : 'true' }, .....

然后在循环中添加动态名称

<p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header" [style]="col.Style" [sortable]="col.sort"></p-column>