3

I get data in the form of array [ 'one', 'two', 'three', 'four', 'five', 'six'] I want to display it in tabular format as follows,

    <table>
    <caption> Numbers:</caption>
    <tr>
        <td>one</td>
        <td>two</td>
        <td>three</td>
    </tr>
    <tr>
        <td>four</td>
        <td>five</td>
        <td>six</td>
    </tr>
    </table>

Can above template dynamically generated using ngFor & ngIf?

So at each ( index % 3 ) = 0 we will draw new row but how do we do that in HTML with angular directives?

The trick here is the incoming array may have any random number of strings.

2
  • 1
    AngularJS or Angular 2+ ? Commented Jun 12, 2019 at 9:14
  • @Jivan Angular 2+ Commented Jun 12, 2019 at 9:38

2 Answers 2

7
<table>
    <caption> Numbers:</caption>
    <ng-container *ngFor="let item of items; let i=index;">
        <tr *ngIf="i % 3 == 0">
            <ng-container *ngFor="let pos of [1, 2, 3]">
                <td *ngIf="i+pos < items.length">{{items[i+pos]}}</td>
            </ng-container>
        </tr>
    </ng-container>
</table>

I haven't tested this, but it should do it.

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

1 Comment

Just minor correction use index 0 instead of 1 for let pos of [1, 2, 3]
1

Try this (TS file):

  data = ['one', 'two', 'three', 'four', 'five', 'six'];
  results: any[] = [];

  constructor() {
    this.results = this.groupColumns(this.data);
  }

  groupColumns(arrays) {
    const newRows = [];
    for (let index = 0; index < arrays.length; index += 3) {
      newRows.push(arrays.slice(index, index + 3));
    }
    return newRows;
  }

in HTML:

<table>
    <caption> Numbers:</caption>
    <tr *ngFor="let result of results">
        <td>{{result[0]}}</td>
        <td>{{result[1]}}</td>
        <td>{{result[2]}}</td>
    </tr>
</table>

Working Demo

2 Comments

Thanks, @Ghoul, But what happens with 5,7 or 10 elements, will that go out of array index?
@pcj, it 's work for any elements , you can test it (working demo)

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.