如何在ngFor中显示span中的动态值

问题描述 投票:0回答:1

我有以下清单

drawingList: any = [
    {id: '1', name:'drawing1', colour_0:'red', colour_1: 'green', colour_2: 'blue'},
    {id: '2', name:'drawing2', colour_0:'black', colour_1: 'white', colour_2: 'brown'}
];

colourSection: Array = ['top', 'middle', 'bottom'] 

我想获取颜色值

<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>

代码运行没有错误,但不显示span中的值。 它只是显示

Section:

html angular
1个回答
0
投票

您不能在字符串内使用字符串插值,而是尝试

+
与索引连接。

<span>Section: {{drawing['colour_' + i]}}</span>

完整代码:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <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>
  `,
})
export class App {
  drawingList: any = [
    {
      id: '1',
      name: 'drawing1',
      colour_0: 'red',
      colour_1: 'green',
      colour_2: 'blue',
    },
    {
      id: '2',
      name: 'drawing2',
      colour_0: 'black',
      colour_1: 'white',
      colour_2: 'brown',
    },
  ];

  colourSection: Array<string> = ['top', 'middle', 'bottom'];
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.