首页 > 解决方案 > 在 Angular 材质表中使用省略号

问题描述

默认情况下,如果内容从包含它的单元格溢出,Angular Material Table 会将内容放在下面的新行中。我正在尝试设置它,以便溢出的文本被截断为“...”。我现在拥有的代码不会截断内容并将其显示在一行中,直到它溢出父级<div>

我使用<table mat-table>而不是因为它具有根据Angular Material Website<mat-table>中描述的内容调整自身大小的列。我试图创建的表是响应式的,并根据其父级的大小调整自身的大小<div>

HTML:

<div class="table-content">
  <table mat-table [dataSource]="dataSource" class="table-container">
    <ng-container [matColumnDef]="item" *ngFor="let item of displayedColumns">
      <th mat-header-cell *matHeaderCellDef>{{item}} </th>
      <td mat-cell *matCellDef="let element">
        <div class="table-data-content">
          <span>{{element[item]}}</span>
        </div>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns;"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>

CSS:

.table-container {
  position: absolute;
  width: 100%;
  height: 100%;
}
.table-data-content {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Angular 组件中使用的示例数据:

  dataSource = [
    { Name: "Some file name that is very long", Date: '08/30/2017', Uploader: 'Some uploader name that is very long'},
    { Name: "Some file name that is very long", Date: '08/30/2017', Uploader: 'Some uploader name that is very long'}
  ];

  displayedColumns = ['Name', 'Date', 'Uploader'];

我可以解决什么问题以在表格中适当使用省略号?

更新: 如果我添加以下 css,省略号有效,我仍然不确定为什么。

td {
max-width: 0px;
}

但是,这种方法破坏了 Angular Material Table 根据内容的长度有效地分配每一列的宽度的方式,因此当另一列仍有大量空白空间时,内容会被截断。有更好的解决方案吗?

标签: cssangularhtml-tableangular-materialangular5

解决方案


您的第一个问题是您将宽度和高度应用于“table-content”,您需要将其直接应用于table tag

尝试这个:

table {
  width: 100%;
  table-layout: fixed;
}

th, td {
  overflow: hidden;
  width:auto;
  text-overflow: ellipsis;
  white-space: nowrap;
}

table标签上使用table-layout:应用了fixed,内容不再决定布局,而是浏览器使用表格第一行中定义的任何宽度来定义列宽。


推荐阅读