You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Angular的ngFor指令逐个展示JSON数组项并支持按钮切换

解决方案

步骤1:修改TypeScript逻辑

新增索引变量控制当前展示项,补全按钮对应方法:

// 新增变量,初始默认展示第一项
currentIndex = 0;
// 用于存储选中的项
selectedItem: any = null;

// 原有jsonItems数组保持不变
jsonItems = [{   
  "ConfidenceLevel": 98.6,
  "Page": 1,
  "DictionaryMaster": {
    "0": {
      "0": "No",
      "1": "94041"
    },
    "1": {
      "0": "Date",
      "1": "08 / 06 / 2020"
    },
    "2": {
      "0": "Due",
      "1": "15 / 06 / 2020"
    },
    "3": {
      "0": " No",
      "1": "113003"
    }
  }
}, { 
  "ConfidenceLevel": 98.56,
  "Page": 1,
  "DictionaryMaster": {
    "0": {
      "0": "Net",
      "1": "\u00a3 212.40"
    },
    "1": {
      "0": "Carriage",
      "1": "\u00a3 0.00"
    },
    "2": {
      "0": "Total  Amount",
      "1": "\u00a3 42.48"
    },
    "3": {
      "0": "Order ",
      "1": "\u00a3 254.88"
    }
  }
}, {
  "CharacterConfidence": 99.72,
  "ConfidenceLevel": 90.26,
  "Page": 1,
  "DictionaryMaster": {
    "0": {
      "0": "Qty  ",
      "1": "  Code",
      "2": "  Description",
      "3": "  Price",
      "4": "  Amount"
    },
    "1": {
      "0": "24",
      "1": "42097805",
      "2": "  Ball  - Red",
      "3": "8.85",
      "4": "212.40"
    },
    "2": {
      "0": "24",
      "1": "42097805",
      "2": "Ball  Red",
      "3": "8.85",
      "4": "212.40"
    },
    "3": {
      "0": "24",
      "1": "42097805",
      "2": " Red",
      "3": "8.85",
      "4": "212.40"
    },
    "4": {
      "0": "24",
      "1": "42097805",
        "2": " - Red",
      "3": "8.85",
      "4": "212.40"
    }
  }
}];

markAsSelected() {
  // 直接获取当前展示的项
  this.selectedItem = this.jsonItems[this.currentIndex];
  // 此处可扩展你的业务逻辑
  console.log('选中的项:', this.selectedItem);
}

showNextItem() {
  // 防止索引超出数组范围
  if (this.currentIndex < this.jsonItems.length - 1) {
    this.currentIndex++;
  } else {
    alert('已经是最后一项');
  }
}

步骤2:修改模板代码

不需要用ngFor遍历整个数组,直接读取当前索引对应的单条数据即可,同时注意Angular的事件绑定语法是(click)而非原生的click属性:

<div class="row" *ngIf="jsonItems[currentIndex] as item">
  <div class="col-3">
    ConfidenceLevel: {{item.ConfidenceLevel}}
    <p>
      <button (click)="markAsSelected()">Select </button>
      <!-- 最后一项时禁用下一页按钮 -->
      <button (click)="showNextItem()" [disabled]="currentIndex >= jsonItems.length -1">Show Next</button>
    </p>
   
  </div>
  <div class="col-9 table-responsive">
    <table class="table  table-bordered">
      <tr *ngFor="let obj of item.DictionaryMaster| keyvalue; let i=index" >
        <ng-container *ngIf="i<2">
          <td *ngFor='let obj1 of obj.value | keyvalue'>
            {{ obj1.value }}
          </td>
        </ng-container>
      </tr>
    </table>
  </div>
</div>

内容的提问来源于stack exchange,提问作者Sebastian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 06:15:02