Angular 7表格行展开异常:点击姓名/地点时展开全部详情的解决方法
解决Angular表格行独立展开/折叠问题
问题原因
你当前使用的expanded1和expanded2是组件级全局变量,所有通过*ngFor循环生成的行都会共享这两个变量状态,导致点击任意一行的姓名或地点时,所有行的对应详情会同步展开/折叠。
解决方案
将每行的展开状态绑定到对应的数据对象上,让每行拥有独立的状态标识:
修改后的app.component.ts
export class AppComponent { data1 = [ { 'name': 'john', 'place': 'forest', 'phone': '124-896-8963', 'expandedName': false, 'expandedPlace': false }, { 'name': 'Jay', 'place': 'City', 'phone': '124-896-1234', 'expandedName': false, 'expandedPlace': false }, { 'name': 'Joseph', 'place': 'sky', 'phone': '124-896-9632', 'expandedName': false, 'expandedPlace': false } ]; }
修改后的app.component.html
<table class="table"> <thead> <th> Name </th> <th> Place </th> <th> Phone </th> </thead> <tbody> <ng-container *ngFor="let data of data1"> <tr> <td (click)="data.expandedName = !data.expandedName"> <a href="javascript:void(0)">{{data.name}}</a> </td> <td (click)="data.expandedPlace = !data.expandedPlace"> <a href="javascript:void(0)">{{data.place}}</a> </td> <td> {{data.phone}} </td> </tr> <ng-container *ngIf="data.expandedName"> <tr> <td colspan="3"> <div>Name Details:{{data.name}}</div> </td> </tr> </ng-container> <ng-container *ngIf="data.expandedPlace"> <tr> <td colspan="3"> <div>Place Details:{{data.place}}</div> </td> </tr> </ng-container> </ng-container> </tbody> </table>
修改说明
- 移除组件中全局的
expanded1、expanded2变量 - 给
data1数组的每个对象新增expandedName和expandedPlace属性,初始值设为false - 点击事件改为切换当前数据项的独立状态属性
- 展开判断条件对应改为当前数据项的状态属性
内容的提问来源于stack exchange,提问作者sarann
相关产品推荐
相关产品推荐

