【问题标题】:How to set the width of an individual column?如何设置单个列的宽度?
【发布时间】:2019-02-10 00:28:33
【问题描述】:

我正在使用Angular DataTables 来显示存储在数据库中的一些数据。有一列名为 description 可以包含大量文本,理想情况下它的宽度应该比其余列大:

我尝试使用columnDefsautoWidth,但没有成功(我单独尝试了两者,也尝试了两者的组合)。在我的component.ts 文件中:

  dtOptions = {
    pagingType: 'full_numbers',
    pageLength: 5,
    scrollX: true,
    autoWidth: false,
    columnDefs: [{width: '40%', targets: 5}]
  };

然后在component.html中

<table datatable [dtOptions]="dtOptions" class="row-border hover" style="width:100%">
  <thead>
      <tr>
        <th *ngFor="let column of feedbackTable.columns">
          {{ column }}
        </th>
      </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of feedbackTable.data">
      <td *ngFor="let cell of row">
        {{cell}}
      </td>
    </tr>
  </tbody>
</table>

scrollX 工作正常,但是,我没有更改列宽。我是否正确使用了dtOptions

当我合并下面的答案时,它仍然不会影响列的宽度:

<th *ngFor="let column of feedbackTable.columns" [class.description]="column === 'user_description'">

 th.description {
    width: 40% !important;
  }

还是给

【问题讨论】:

  • Angular 数据表似乎没有通过dtOptions 设置列宽的选项,但您可以使用 CSS 实现此目的
  • @mkhayata:你能详细说明一下吗?你会在ngFor 部分添加这个吗?
  • 我已经发布了答案
  • 如果你想要精确控制,你需要使用 CSS。请参阅thisthis 答案...
  • @davidkonrad 感谢您的链接!目前正在旅行,所以我只能在几天内测试它。

标签: angular datatables datatables-1.10 angular-datatables


【解决方案1】:

我尝试了这篇文章和其他帖子中数据表选项和 CSS 的所有组合,但没有任何效果。

您需要在数据表呈现后更新列的样式。可能有一个回调我可以从数据表中挂钩以触发操作,但我只是设置了一个快速超时并且它工作正常。在我的 ngOnInit 中:

    setTimeout(()=>{
      let firstColumn = document.querySelector('th');
      firstColumn.setAttribute('style', 'width: 150px !important;');
    }, 10)

如果稍后重新渲染表格,您可能需要再次执行此操作。

【讨论】:

  • 得重新找代码;将近一年没有再调查这个问题了。不过看起来不错,所以我现在给了它一个赞成票:)
【解决方案2】:

您可以使用 CSS 实现这一点,如下所示:

添加 CSS 规则

th.description {
  width: 40%;
}

然后在您的组件模板中,您可以将描述类仅应用于具有 Angular 类绑定的描述列:

<thead>
  <tr>
    <th *ngFor="let column of feedbackTable.columns" [class.description]="column === 'description'">
      {{ column }}
    </th>
  </tr>
</thead>

根据列的 ID 而不是显示的名称来创建条件也会更好,但是您需要将列属性扩充为对象,例如column={id: 'desc', name: 'description'}

使用 ngStyle 更新:

<thead>
  <tr>
    <th *ngFor="let column of feedbackTable.columns" [ngStyle]="{'width':column === 'description' ? '100px' : '' }">
      {{ column }}
    </th>
  </tr>
</thead>

【讨论】:

  • 谢谢!不幸的是,它似乎没有任何效果;当我检查元素时,它仍然显示任意宽度。我会多玩一点,然后 - 如果它有效 - 投票并接受......
  • 数据表可能正在使用另一个 CSS 类设置宽度,其优先级高于您的 description 类。尝试更新您的 CSS 规则 width: 40% !important,如果这可行,那么为了更好的做法,删除 !important 并增强您的 CSS 规则以获得比数据表提供的更高的优先级。
  • !important 也无济于事;将进行调查。
  • 好的,您可以从 devtool 发布检查,看看可能是什么问题。
  • 我编辑了我的问题并添加了截图。如果您能看一下,将不胜感激,谢谢!
猜你喜欢
  • 2017-01-19
  • 2014-01-19
  • 1970-01-01
  • 2015-05-22
  • 2015-10-02
  • 1970-01-01
  • 2023-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多