[FIXED] Getting duplicate data in Angular HTML table (PrimeNG)

Issue

If there is one data it will display only one raw. If there are two data then it will show fore rows, if there are there data then it will display nine rows. I think in my component.ts file is the problem.

data is getting from laravel(Back End)

itemlist.component.ts

import { NgStyle } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Project } from '@root/shared/classes/project';
import { DataService } from '@root/shared/services/data.service';

@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html',
  styleUrls: ['./item-list.component.scss']
})
export class ItemListComponent implements OnInit {

  projects:any;

  project = new Project();

  constructor(private dataService:DataService) { 

  }

  ngOnInit(): void {
    this.getProjectsData();

  }

  //get project data into the table
  getProjectsData() {
    this.dataService.getProjectData().subscribe(res => {
      this.projects = res;
    })
  }
}

itemlist.component.html

<p-table [value]="projects" styleClass="p-datatable-gridlines" responsiveLayout="scroll" scrollHeight="17.8vw">
  <ng-template pTemplate="header">
    <tr>
      <th style="text-align: center;" translate>itemlist.customer <br> itemlist.name</th>
      <th style="text-align: center;" translate>itemlist.project <br> itemlist.name</th>
      <th style="text-align: center;" translate>itemlist.business <br> itemlist.divition</th>
      <th style="text-align: center;" translate>itemlist.rank</th>
      <th style="text-align: center;" translate>itemlist.order <br> itemlist.amount</th>
      <th style="text-align: center;" translate>itemlist.customer <br> itemlist.area</th>
  </ng-template>
  <ng-template pTemplate="body"> 
    <tr *ngFor="let pjt of projects">
      <td style="text-align: center;">{{ pjt.customer_name }}</td>
      <td style="text-align: center; width: 15vw;">{{ pjt.project_name_jp }}</td>
      <td style="text-align: center;">{{ pjt.business_divition }}</td>
      <td style="text-align: center;">{{ pjt.rank }}</td>
      <td style="text-align: center;">{{ pjt.order_amount }}</td>
      <td style="text-align: center;">{{ pjt.customer_area }}</td>
    </tr>
  </ng-template>
</p-table>

Solution

Remove *ngFor="let pjt of projects" and use let variable.

<ng-template pTemplate="body" let-pjt>
  <tr>
    ...
  </tr>
</ng-template>

Sample Solution on StackBlitz


References

Table Templating | PrimeNG


Answered By – Yong Shun

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published