Iterate Tables and Labels Using ngFor in Angular

Issue

I’m trying to make several tables with a several label heading. The label heading should be the project.name. On each project.name, it will have the table material_projects. In it it will have heading of material_name, quantity, unit and total. I have the example picture below on how would I want to achieve this. I’ve also added the api response below. I’m confused on how would I iterate using the *ngFor in the html.

Table

json response

getAllProjects() {
    this.subscription = this.projectsService.getAll()
      .subscribe(
        (data:any) => {
          this.projects = data.projects;
          console.log(data);
        },
        error => {
          console.log(error);
        });
  }

html

<div class="card-block">
  <table class="table table-bordered table-striped">
    <thead>
      <tr>
        <th>Project Name</th>
        <th>Material ID</th>
        <th>Unit</th>
        <th>Quantity</th>
        <th>Total Quantity</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let project of projects">
        <td>{{ project.name }}</td>
        <td>{{ project.material_projects.material_id}}</td>
        <td>{{ project.material_projects.unit }}</td>
        <td>{{ project.material_projects.quantity }}</td>
        <td>{{ project.material_projects.total }}</td>
      </tr>
    </tbody>
  </table>
</div>

Solution

You can do something like this,

<div *ngFor="project of projects">
  {{project.name}}
  <table>
    <th>
      <td>material_id</td>
      <td>quantity</td>
      <td>Unit</td>
      <td>total</td>
    </th>
    <tr *ngFor="innerItem of project.material_projects">
      <td>{{innerItem.id}}</td>
      <td>{{innerItem.quantity}}</td>
      <td>{{innerItem.unit}}</td>
      <td>{{innerItem.total}}</td>
    </tr>
  </table>
</div>

Answered By – AddWeb Solution Pvt Ltd

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.