Search code examples
htmlangular

How to display dynamic value in span in ngFor


I have the following lists

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

I want to get the colours value

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

Code serves without error, but does not display the value in span. It just displays Section:


Solution

  • You cannot use string interpolation inside a javascript context string (notice that the string is inside curly braces), instead try + join with the index.

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

    Full Code:

    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 Demo