Ranindu
Ranindu

Reputation: 1063

How to display object of array data on html table in Angular

I need to display below object of array in html table like that image. My data array like this.

data = [{id: 0 , name: 'one' , tags: ['a' , 'b' , 'c']} , {id: 1 , name: 'two', tags: ['r' , 't' , 'y']} , {id: 2 , name: 'three' , tags: ['a' , 'b' , 'c']} , {id: 3 , name: 'four' , tags: ['a' , 'b' , 'c']}]; .

enter image description here

So i tried like this but it's not working as expect on image.

 <table class="table table-hover table-bordered">
    <thead>
    <tr>
        <th scope="col">Tag Type</th>
        <th scope="col">Tags</th>
        <th scope="col">Action</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let tag of data; let i = index">
        <td>{{ tag.id }}</td>
            <table class="table">
            <tr *ngFor="let el of tag.tags">
              <td>{{el}}</td>
            </tr>
            </table>
        <td>
            <div align="center">
              <a matTooltip="edit tag"><i>mode_edit</i></a>
            </div>
        </td>
    </tr>

    </tbody>
</table> 

this is the result i got.Any idea how to do this?

enter image description here

Upvotes: 1

Views: 2653

Answers (1)

Shantanu Bharatia
Shantanu Bharatia

Reputation: 61

I have made a few modifications into the code. Instead of creating a new nested table,I have tried create separate rows in the main table. I have hid the TagType And Action, where it is not to be displayed based on the index. For the striped pattern, I have added "table-striped" class to the table.

The Html code would look like this

<table class="table table-hover table-bordered table-striped">
  <thead>
    <tr>
      <th scope="col">Tag Type</th>
      <th scope="col">Tags</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <ng-container *ngFor="let tag of data; let i = index">
      <tr *ngFor="let el of tag.tags; let i2=index">

        <td *ngIf="i2==0"> {{tag.id}} </td>
        <td *ngIf="i2!=0"> </td>
        <td> {{el}} </td>
        <td>
          <div align="center">
            <a matTooltip="edit tag"><i>mode_edit</i></a>
          </div>
        </td>
      </tr>
    </ng-container>

  </tbody>
</table>

StackBlitz working demo: https://stackblitz.com/edit/angular-ivy-aqmrzy

Upvotes: 1

Related Questions