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

Angular中如何在ngFor的span内显示动态属性值?

问题解决:Angular模板中动态访问对象属性失败

问题原因

你在模板中尝试用drawing['colour_{{i}}']动态访问属性的写法是错误的——Angular模板不支持嵌套插值{{}},这里的'colour_{{i}}'会被当作字面量字符串,而非动态拼接的属性名。程序会去drawing对象里查找名为colour_{{i}}的属性,显然这个属性不存在,所以最终显示空值。

另外注意:ngFor的表达式分隔符应该用分号而非逗号,正确写法是*ngFor="let section of colourSection; let i = index",虽然逗号可能不会报错,但不符合Angular语法规范。

解决方案

有两种简洁的解决方式:

方式1:模板内直接字符串拼接

直接在属性访问中用'colour_' + i完成动态拼接,这是最直接的写法:

<ng-container *ngFor="let drawing of drawingList">
     <ng-container *ngFor="let section of colourSection; let i = index">
           <div class="attribute-row">
                 <span>Section: {{ drawing['colour_' + i] }}</span>
           </div>
     </ng-container>
</ng-container>

方式2:组件内添加辅助方法

如果后续逻辑更复杂,或者想让模板更简洁,可以在组件类中定义一个方法来封装属性访问逻辑:
组件代码:

// 组件类中添加此方法
getColour(drawing: any, index: number): string {
  // 使用模板字符串拼接属性名
  return drawing[`colour_${index}`];
}

模板调用:

<ng-container *ngFor="let drawing of drawingList">
     <ng-container *ngFor="let section of colourSection; let i = index">
           <div class="attribute-row">
                 <span>Section: {{ getColour(drawing, i) }}</span>
           </div>
     </ng-container>
</ng-container>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:42:37