Angular 7中如何不修改JSON数据实现表格行展开折叠
Angular 7表格行展开折叠(不修改原JSON数据)
完全可行,不用给原JSON数据加任何属性,只需要在组件里单独维护每行的展开状态就行,给你两种常用实现方式:
方式一:用对象存储状态(基于数据项的唯一标识)
如果你的数据项有唯一标识(比如示例里的name,实际项目里建议用id),可以用一个独立对象来存每行的展开状态:
修改后的app.component.ts:
import { Component, OnInit } from '@angular/core'; export class AppComponent implements OnInit{ // 用对象存储每行的展开状态,键为数据项的唯一标识 expandedStates: {[key: string]: boolean} = {}; data1 = [ { name: 'john', place: 'forest', phone: '124-896-8963' }, { name: 'Jay', place: 'City', phone: '124-896-1234' }, { name: 'Joseph', place: 'sky', phone: '124-896-9632' }, ]; ngOnInit(){ // 初始化所有行默认折叠 this.data1.forEach(item => { this.expandedStates[item.name] = false; }); } // 切换指定行的展开状态 toggleExpand(item: any) { this.expandedStates[item.name] = !this.expandedStates[item.name]; } }
对应的模板(app.component.html):
<table> <thead> <tr> <th>姓名</th> <th>地点</th> <th>电话</th> <th>操作</th> </tr> </thead> <tbody> <tr *ngFor="let item of data1"> <td>{{item.name}}</td> <td>{{item.place}}</td> <td>{{item.phone}}</td> <td> <button (click)="toggleExpand(item)"> {{expandedStates[item.name] ? '折叠' : '展开'}} </button> </td> </tr> <!-- 展开内容行 --> <tr *ngFor="let item of data1" *ngIf="expandedStates[item.name]"> <td colspan="4"> 这是{{item.name}}的展开内容,比如详细信息:{{item.phone}} - {{item.place}} </td> </tr> </tbody> </table>
方式二:用Map存储状态(支持对象作为键)
如果数据项没有合适的唯一标识,或者想更灵活,可以用ES6的Map,它支持直接把数据对象作为键来存储状态:
修改后的app.component.ts:
import { Component, OnInit } from '@angular/core'; export class AppComponent implements OnInit{ // 用Map存储展开状态,键为数据对象本身 expandedMap = new Map<any, boolean>(); data1 = [ { name: 'john', place: 'forest', phone: '124-896-8963' }, { name: 'Jay', place: 'City', phone: '124-896-1234' }, { name: 'Joseph', place: 'sky', phone: '124-896-9632' }, ]; ngOnInit(){ // 初始化所有行默认折叠 this.data1.forEach(item => { this.expandedMap.set(item, false); }); } // 切换指定行的展开状态 toggleExpand(item: any) { const currentState = this.expandedMap.get(item) || false; this.expandedMap.set(item, !currentState); } }
对应的模板调整:
<table> <thead> <tr> <th>姓名</th> <th>地点</th> <th>电话</th> <th>操作</th> </tr> </thead> <tbody> <tr *ngFor="let item of data1"> <td>{{item.name}}</td> <td>{{item.place}}</td> <td>{{item.phone}}</td> <td> <button (click)="toggleExpand(item)"> {{expandedMap.get(item) ? '折叠' : '展开'}} </button> </td> </tr> <!-- 展开内容行 --> <tr *ngFor="let item of data1" *ngIf="expandedMap.get(item)"> <td colspan="4"> 这是{{item.name}}的展开内容,比如详细信息:{{item.phone}} - {{item.place}} </td> </tr> </tbody> </table>
这两种方式都不会修改原JSON数据,完全符合你的需求,选哪种取决于你的数据结构和实际场景。
内容的提问来源于stack exchange,提问作者sarann
相关产品推荐
相关产品推荐

