Search code examples
angularngforstring-interpolation

How to combine string and array in string interpolation of ngfor in Angular


I have an array of objects, I would like to combine a string and an array while showing in ngfor iteration.

temp: [
  {
    "value1": "as",
    "value2": "[a, b, c, d, e]",
    "value3": "alphabets"
  },
  {
    "value1": "qw",
    "value2": "[aa, bb, cc, dd, ee]",
    "value3": "alphas"
  }

I want to show data as

Column A Column B
as alphabets, a, b, c, d e
qw alphas, aa, bb, cc, dd, ee

Thank you in advance.

I tried to concat the string and array but the array is appearing as array not string.

Have to do this in template file only. Otherwise, we can alter the object to achieve this.


Solution

  • You can create a new array which stores the transformed value.

    Here we use the regex /[\[\]]/g to which matches the characters [ and ] and replaces it with empty string, finally we join the values on the array.

    We can use @for to loop and create the rows.

    I am creating a new array, because my other solution involves transforming using a function, which runs everytime during change detection, so this method below is better for performance.

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
      
    <table style="width:100%">
      <tr>
        <th>Column A</th>
        <th>Column B</th> 
      </tr>
        @for(item of tempTransformed;track $index) {
      <tr>
        <td>{{item.value1}}</td>
        <td>{{item.value3}}, {{item.value2}}</td>
      </tr>
        }
    </table>
    
      `,
    })
    export class App {
      temp: Array<any> =  [
        {
          value1: 'as',
          value2: '[a, b, c, d, e]',
          value3: 'alphabets',
        },
        {
          value1: 'qw',
          value2: '[aa, bb, cc, dd, ee]',
          value3: 'alphas',
        }
      ];
      tempTransformed: Array<any> = [];
      ngOnInit() {
        this.tempTransformed = this.temp.map((item: any) => {
          item.value2 = item.value2.replaceAll(/[\[\]]/g, '');
          return item;
        });
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo


    Same code but with *ngFor

    Stackblitz Demo