如何根据首个键值将对象数组填充到Angular表格中
Angular表格数据匹配与逻辑渲染实现
步骤1:在组件类中添加数据匹配与逻辑方法
在app.component.ts中,添加用于匹配分数、判断处置状态的方法:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { tabs = ['Sample #1', 'Sample #2', 'Sample #3']; scorePerSample: any[] = [ { sampleNo: 0, score: 1, }, { sampleNo: 2, score: 10, }, { sampleNo: 1, score: 3, }, ]; // 根据sampleNo获取对应分数 getScore(sampleNo: number): number { const matchedItem = this.scorePerSample.find(item => item.sampleNo === sampleNo); return matchedItem ? matchedItem.score : 0; // 无匹配时默认返回0,可按需调整 } // 获取处置状态文本 getDisposition(sampleNo: number): string { const score = this.getScore(sampleNo); return score > 2 ? 'Reject' : 'Good'; } // 获取处置分数 getDispositionScore(sampleNo: number): number { return this.getDisposition(sampleNo) === 'Reject' ? 1 : 0; } }
步骤2:修改模板代码实现数据绑定
更新app.component.html中的表格模板,绑定对应方法实现数据渲染:
<div class="row"> <div class="col-sm-12"> <div class="table-responsive"> <table class="table table-bordered table-hover" id="scoreTable"> <thead class="thead-light"> <tr> <th scope="col">Sample</th> <th scope="col">Decision Score</th> <th scope="col">Disposition Per Sample</th> <th scope="col" class="d-none">Disposition Score</th> </tr> </thead> <tbody> <tr *ngFor="let tab of tabs; let idx = index"> <td>{{ tab }}</td> <td>{{ getScore(idx) }}</td> <td>{{ getDisposition(idx) }}</td> <td class="d-none">{{ getDispositionScore(idx) }}</td> </tr> </tbody> </table> </div> </div> </div>
逻辑说明
- 分数匹配:通过
getScore方法,利用循环的索引idx对应sampleNo,从scorePerSample数组中找到匹配的分数并返回。 - 处置状态判断:分数大于2时显示
Reject,否则显示Good。 - 处置分数映射:
Reject对应1,Good对应0。
内容的提问来源于stack exchange,提问作者Rak
相关产品推荐
相关产品推荐

