Angular 4 ngFor循环中TD内容按需展开/收起的问题求助
嘿,这个问题我之前做项目时也碰到过!核心问题就是你用了一个全局的truncating变量,循环里所有的列表项都共享它的状态,所以一点击按钮就全跟着切换了。别担心,咱们给每个列表项搞个独立的控制状态就行,这里有两种简单靠谱的方案:
方案一:给每个列表项添加独立的状态属性
如果不介意给原列表对象增加额外属性,可以直接在获取到数据后,给每个item加上截断状态:
组件代码(TypeScript)
// 假设你是在接口请求成功后处理数据 this.yourDataService.getList().subscribe(data => { this.newList.all = data; // 给每个列表项添加默认的截断状态(初始为true,即显示截断内容) this.newList.all.forEach(item => { item.isTruncated = true; }); });
模板代码(HTML)
把原来的全局truncating变量换成每个item自己的isTruncated属性,按钮点击也只操作当前item的状态:
<ng-container *ngFor="let list of newList.all;let i = index"> <tr [class.my-class]="i == selectedRow || currentPlayingId == list.id"> <td> {{list.id }} </td> <td> <!-- 根据当前item的状态决定是否截断 --> {{ list.filename || list.url || list.eventurl | truncate : (list.isTruncated ? 20 : undefined) }} </td> <!-- 优化:只有内容长度超过20时才显示按钮 --> <button *ngIf="(list.filename || list.url || list.eventurl)?.length > 20" ion-button (click)="list.isTruncated = false" > show more </button> <button *ngIf="(list.filename || list.url || list.eventurl)?.length > 20 && !list.isTruncated" ion-button (click)="list.isTruncated = true" > show less </button> <td class="textSize"> {{list.mode }} </td> </tr> </ng-container>
方案二:维护独立的状态对象(不污染原数据)
如果不想修改原列表的结构(比如这个列表还要传给其他组件使用),可以单独维护一个对象,用列表项的id作为键来存储每个项的状态:
组件代码(TypeScript)
// 定义一个对象存储每个item的截断状态 truncationStates: { [key: number]: boolean } = {}; // 初始化状态 this.yourDataService.getList().subscribe(data => { this.newList.all = data; this.newList.all.forEach(item => { // 用item的id作为键,默认设置为true this.truncationStates[item.id] = true; }); });
模板代码(HTML)
通过truncationStates[list.id]来访问当前item的状态:
<ng-container *ngFor="let list of newList.all;let i = index"> <tr [class.my-class]="i == selectedRow || currentPlayingId == list.id"> <td> {{list.id }} </td> <td> {{ list.filename || list.url || list.eventurl | truncate : (truncationStates[list.id] ? 20 : undefined) }} </td> <button *ngIf="(list.filename || list.url || list.eventurl)?.length > 20" ion-button (click)="truncationStates[list.id] = false" > show more </button> <button *ngIf="(list.filename || list.url || list.eventurl)?.length > 20 && !truncationStates[list.id]" ion-button (click)="truncationStates[list.id] = true" > show less </button> <td class="textSize"> {{list.mode }} </td> </tr> </ng-container>
两种方案都能解决你的问题,选哪种取决于你是否愿意修改原数据结构~
内容的提问来源于stack exchange,提问作者user4785698
相关产品推荐
相关产品推荐

