1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response. I just got to know the value2 will come as an array and can be done using ng-container in template file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.