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

Angular模板中如何遍历接口属性动态访问对象字段

Angular 模板遍历接口动态属性实现方案

问题背景

对接 TheMealDB 食谱接口时,返回的单条食谱数据包含 20 个带数字后缀的食材字段 strIngredient1 ~ strIngredient20、20 个对应用量字段 strMeasure1 ~ strMeasure20,逐字段手动编写模板代码冗余度极高。尝试通过序号拼接属性名的写法 {{ recipe.strIngredient+ number }} 无法正常获取属性值。

接口返回数据结构参考:

{
  idMeal: number,
  strMeal: string,
  strCategory: string,
  strArea: string,
  strInstructions: string,
  strMealThumb: string,
  strIngredient1: string,
  strIngredient2: string,
  // 中间省略 strIngredient3 ~ strIngredient19
  strIngredient20: string,
  strMeasure1: string,
  strMeasure2: string,
  // 中间省略 strMeasure3 ~ strMeasure19
  strMeasure20: string,
}

失效原因

原有写法通过 . 取到 strIngredient 属性后直接拼接数字,本质是执行字符串拼接运算,而非访问对象的动态属性,最终无法得到预期的字段值。

可行实现方案

方案1:模板内通过方括号语法访问动态属性

无需额外处理组件逻辑,直接在 Angular 模板中使用 JS 原生的方括号动态属性访问语法,通过拼接完整属性名字符串取值即可,同时可增加空值判断过滤无效条目。

首先在组件 TS 中定义循环用的序号数组:

// 生成1~20的序号数组,对应接口字段的数字后缀
readonly loopNums = Array.from({ length: 20 }, (_, idx) => idx + 1);
recipe: any; // 存储接口返回的食谱数据

模板代码调整为:

<div 
  class="d-flex custom-control align-items-center" 
  *ngFor="let num of loopNums"
>
  <i class="fa-solid fa-circle-check mr-2"></i>
  <!-- 过滤食材名为空的无效条目 -->
  <p class="ingred-paragraph" *ngIf="recipe['strIngredient' + num]?.trim()">
    {{ recipe['strMeasure' + num]?.trim() }} {{ recipe['strIngredient' + num]?.trim() }}
  </p>
</div>

方案2:TS层预处理为结构化数据(推荐)

在拿到接口返回数据后,先在 TS 逻辑层把零散的食材、用量字段整理为结构化数组,模板直接遍历结构化数组即可,代码可维护性更高,也避免模板中写过多逻辑。

TS 层处理代码:

interface IngredientPair {
  name: string;
  measure: string;
}
ingredientList: IngredientPair[] = [];

// 接口请求成功拿到recipe数据后,调用该方法处理食材字段
formatIngredients(recipe: any) {
  this.ingredientList = [];
  for (let i = 1; i <= 20; i++) {
    const ingName = recipe[`strIngredient${i}`]?.trim();
    const ingMeasure = recipe[`strMeasure${i}`]?.trim();
    if (ingName) {
      this.ingredientList.push({
        name: ingName,
        measure: ingMeasure
      });
    }
  }
}

模板代码可简化为:

<div 
  class="d-flex custom-control align-items-center" 
  *ngFor="let item of ingredientList"
>
  <i class="fa-solid fa-circle-check mr-2"></i>
  <p class="ingred-paragraph">
    {{ item.measure }} {{ item.name }}
  </p>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:57:31