【问题标题】:How to set the width of a column of a dynamic HTML table如何设置动态 HTML 表格的列宽
【发布时间】:2020-09-15 00:45:40
【问题描述】:

我的代码如下

 <table >
    <thead >
        <th *ngFor="let col of workData.columns;trackBy: trackByColumn;
            let hindex=index;" [ngClass]="setWidth(col)" [index]="hindex">
        </th>
    </thead>
</table>


 //TS File

  setWidth(col){
   if(col.field === 'First Name') {
   col.width = '100px';
 }
}

在上表中,我从 Http 调用中获取了列名 List 和列 Data 并基于它呈现表。 如何根据名称动态设置每列的宽度。

例如:

Column: First Name Width:100px Column: Last Name Width:90px Column: Address Width: 150px

我正在使用Angular 6。我尝试了javascript解决方案以及ngClassngStyle的角度。但我无法掌握如何为每列设置宽度。

【问题讨论】:

    标签: html css angular html-table width


    【解决方案1】:

    [ngClass] 需要一个对象。您正在调用一个不返回任何内容的方法

    一种可能的方法是绑定style 属性。

    component.ts

      public styles=
      {
        'First Name' : '100px',
        'Last Name' : '90px',
        'Address' : '150px'
      };
    

    component.html

     <table >
        <thead >
            <th [style.width]="styles[col.field]" 
                *ngFor="let col of workData.columns; let hindex=index;" >
              {{col.field}}
            </th>
        </thead>
    </table>
    

    Stackblitz demo

    你可以对类做同样的事情(例如class=classes[col.field]

    【讨论】:

      【解决方案2】:

      您可以创建一个带有“样式”属性的 JSON 对象,如下所示:

      workData = { columns: [ { field: "First Name", style: { width: "100px", "background-color": "red", color: "white" } }, { field: "Last Name", style: { width: "200px", "background-color": "blue", color: "white" } }, { field: "Address", style: { width: "300px", "background-color": "yellow", color: "black" } } ]};

      然后在你的 file.html 中

      <table>
       <thead>
        <th [ngStyle]="col.style" *ngFor="let col of workData.columns;">{{col.field}}</th>
       </thead>
      </table>
      

      现在您可以在桌子上添加多个样式

      click here to see it running

      【讨论】:

        猜你喜欢
        • 2012-08-13
        • 2010-11-04
        • 2023-03-10
        • 1970-01-01
        • 2014-05-24
        • 1970-01-01
        • 2016-06-28
        • 2014-11-19
        • 2012-04-01
        相关资源
        最近更新 更多