1

I have an array of Strings like below :

nameArray = ["Str1","Str2","Str3","Str4",......];

I need to display this data into tabular format with three columns like below :

Col1       Col2       Col3
--------------------------
Str1       Str2       Str3

Str4       Str5       Str6

Str7       Str8       .....

Need help to write logic to display the above data in Angular, TypeScript.

0

2 Answers 2

1

Controller

export class AppComponent  {
  input = ["Str1", "Str2", "Str3", "Str4", "Str5", "Str6", "Str7", "Str8", "Str9", "Str10"];
  output = [];

  constructor() {
    const size = 3;
    for (var i=0; i < this.input.length; i+=size) {
      this.output.push(this.input.slice(i, i+size));
    }
  }
}

Template

<table>
  <tr>
    <ng-container *ngFor="let item of output; let i=index; let last=last">
      <ng-container *ngIf="!last">
        <th>
          Col {{i + 1}}
        </th>
      </ng-container>
    </ng-container>
  </tr>
  <tr *ngFor="let item of output">
    <td *ngFor="let col of item">
      {{ col }}
    </td>
  </tr>
</table>

Working example: Stackblitz

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

Comments

0

toTable function will split nameArray required column chunks. it takes an optional parameter for no of columns, defaults to 3

  public nameArray = ["Str1","Str2","Str3","Str4",'st5', 'st6', 'st7', 'st8', 'st9'];
  public data = [];
  public columns = [];
  public toTable ( columns=3 ) {
    let i = 1;
    while ( i <= columns ) {
      this.columns.push ( `Col${i}`);
      i += 1;
    }
    for (let i=0,j=this.nameArray.length; i<j; i+=columns) {
        this.data.push ( this.nameArray.slice(i,i+columns));        // do whatever
    }
  }

Use this html template for rendering the info in a table format

<table>
  <thead>
    <tr><th *ngFor="let column of columns">{{column}}</th></tr>
  </thead>
  <tr *ngFor="let node of data" >
    <td *ngFor="let point of node">{{point}}</td>
  </tr>
</table>

Comments

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.