角度材料表单元格不截断长文本



我正在使用Angular Material的表和Bootstrap的声明式css。尽管将表格的宽度和最大宽度设置为 100%,但一列无法正确截断文本。未设置容器的宽度时,通常会发生此问题。我应该在材质表上应用哪些类来截断长文本。

<div class="col flex-grow-1 min-height-0 m-0 p-0">
<div class="h-100 overflow-auto">
<table *ngIf="trunks | async as data" mat-table
[dataSource]="data.entities"
class="w-100">
<ng-container matColumnDef="select">
... Checkbox logic
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>
... Header logic, this is much shorter than the offending name
</ng-container>
</th>
<td mat-cell *matCellDef="let trunk" class="text-truncate">
<div class="d-inline text-truncate">
... Status icon logic, width of < 40px
<a [routerLink]="['./' + trunk.id]" [queryParams]="{}" queryParamsHandling="merge"
class="text-truncate">{{ trunk.name }}</a>
</div>
</td>
</ng-container>
... Other cells with short text
</table>
</div>
</div>

trunk.name是用户输入的,因此最终必须将其截断。

堆栈闪电战

https://stackblitz.com/edit/angular-c2menq?file=app/table-basic-example.css

我会推荐一种纯CSS方法来解决这个问题。

.truncate-cell {
max-width: 60px; /* feel free to include any other value */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

在组件.html上,您可以简单地将 CSS 类添加到该单元格。

<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element" class="truncate-cell"> {{element.name }} </td>
</ng-container>

这会导致 mat-cell 中的字符串包含在一行中,从而其容器的overflow属性设置为hidden

您可以在此处阅读有关text-overflow属性的更多信息。

我还在这里分叉了一个演示。

创建自定义管道:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, args: any[]): string {
const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
const trail = args.length > 1 ? args[1] : '...';
return value.length > limit ? value.substring(0, limit) + trail : value;
}
}

现在您可以使用它:

<ng-container matColumnDef="comment">
<th mat-header-cell *matHeaderCellDef>Comment</th>
<td mat-cell *matCellDef="let pack" class="truncate-cell"><span>{{pack.comment | truncate:[20, '...']}}</span></td>
</ng-container>

最新更新