Angular 13表格序列号去重显示:递增位数+省略号实现方案咨询
在Angular 13中实现序列号智能显示逻辑
核心思路
先计算出能让所有序列号唯一区分的最小末尾显示长度(从默认5位开始递增),再生成对应省略号+末尾片段的显示文本,同时利用原生title属性实现鼠标悬停显示完整序列号。
步骤1:预处理序列号数据(性能优先方案)
在组件中提前处理所有序列号,计算好每个条目显示文本,避免模板中重复计算:
import { Component, OnInit } from '@angular/core'; interface SerialEntry { full: string; display: string; } @Component({ selector: 'app-serial-table', templateUrl: './serial-table.component.html' }) export class SerialTableComponent implements OnInit { // 原始序列号数组 rawSerialNumbers = [ 'SNM1A892P4JRI3LKI1701205001002ANKSC', 'SNM1A892P4JRI3LKI17012050010026ANKSC', 'SNM1A892P4JRI3LKI1701205001003ANKSC', 'SNM1A892P4JRI3LKI1701205001003BANKSC' ]; processedEntries: SerialEntry[] = []; ngOnInit(): void { this.processSerialNumbers(); } private processSerialNumbers(): void { // 找到能区分所有序列号的最小末尾长度 const uniqueEndLength = this.getUniqueEndLength(this.rawSerialNumbers); // 为每个序列号生成显示文本 this.processedEntries = this.rawSerialNumbers.map(sn => { const actualEndLength = Math.min(uniqueEndLength, sn.length); const endSegment = sn.slice(-actualEndLength); // 生成省略号,保持显示总长度为10(省略号数+末尾位数) const ellipsis = '.'.repeat(Math.max(0, 10 - actualEndLength)); return { full: sn, display: `${ellipsis}${endSegment}` }; }); } private getUniqueEndLength(sns: string[]): number { let currentLength = 5; const maxPossibleLength = Math.max(...sns.map(sn => sn.length)); // 循环递增长度,直到所有末尾片段唯一 while (currentLength <= maxPossibleLength) { const endSegments = sns.map(sn => sn.slice(-currentLength)); if (new Set(endSegments).size === endSegments.length) { return currentLength; } currentLength++; } // 极端情况:所有序列号完全相同,返回最大长度 return maxPossibleLength; } }
步骤2:模板渲染与悬停显示
在模板中遍历处理后的条目,用title属性绑定完整序列号实现悬停显示:
<table border="1"> <thead> <tr> <th>序列号</th> </tr> </thead> <tbody> <tr *ngFor="let entry of processedEntries"> <td [title]="entry.full">{{ entry.display }}</td> </tr> </tbody> </table>
可选:用管道实现(动态数据场景)
如果序列号数组会频繁更新,可以用Angular管道封装逻辑,注意设置pure: false以响应数组内容变化:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'serialDisplay', pure: false }) export class SerialDisplayPipe implements PipeTransform { transform(serial: string, allSerials: string[]): string { let currentLength = 5; const maxLength = Math.max(...allSerials.map(s => s.length)); while (currentLength <= maxLength) { const segments = allSerials.map(s => s.slice(-currentLength)); if (new Set(segments).size === segments.length) break; currentLength++; } const actualLength = Math.min(currentLength, serial.length); const endSegment = serial.slice(-actualLength); const ellipsis = '.'.repeat(Math.max(0, 10 - actualLength)); return `${ellipsis}${endSegment}`; } }
模板中使用管道:
<td [title]="sn">{{ sn | serialDisplay: rawSerialNumbers }}</td>
边界情况处理
- 当序列号长度小于计算出的唯一长度时,直接显示完整序列号,省略号自动隐藏
- 当所有序列号完全相同时,显示完整内容,省略号为0
内容的提问来源于stack exchange,提问作者RAKSHA
相关产品推荐
相关产品推荐

