How to use Skeleton in PrimeNG DataTable when retrieving data from a Rest API?

I am trying to display Skeleton in a PrimeNG DataTable while retrieving information from a REST API.

When the information is received Skeleton should hide and display the data.

There is a example: https://primeng.org/skeleton#datatable

But this example does not show how to substitute the Skeleton for the data received.

Upvotes: 0

Views: 867

Answers (2)

Ilias Et-taymy
Ilias Et-taymy

Reputation: 1

To show a Skeleton in a PrimeNG DataTable while fetching data from a REST API:

  • set up your component and service;
  • create a boolean 'loading' variable initialized to true;
  • define skeleton and table columns using pTemplate
  • conditionally render the Skeleton or data table with *ngIf based on 'loading'
  • and set 'loading' to false once data is retrieved.

api.service.ts api.service.ts

app.component.html app.component.html

app.component.ts app.component.ts

Upvotes: 0

AhmedSHA256
AhmedSHA256

Reputation: 663

The example doesn't show how to replace it because it is just an example. What I suggest is adding a boolean initialized as true, and change it to false when the subscription ends. You can try this:

export class Foo implements OnInit {
  isLoading: boolean = true;

  constructor(private fooService: FooService) {}

  ngOnInit() {
    this.fooService.getBar().subscribe(data => {
      ...your code
      this.isLoading = false;
    });
  }
}

And the HTML (following the primeng example) would be this:

<p-table [value]="products" [tableStyle]="{ 'min-width': '50rem' }">
  <ng-template pTemplate="header">
    <tr>
      <th>Code</th>
      <th>Name</th>
      <th>Category</th>
      <th>Quantity</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-product>
    <tr>
      <td *ngIf="!isLoading; else loading">{{ product.code }}</td>
      <td *ngIf="!isLoading; else loading">{{ product.name }}</td>
      <td *ngIf="!isLoading; else loading">{{ product.category }}</td>
      <td *ngIf="!isLoading; else loading">{{ product.quantity }}</td>
      <ng-template #loading>
        <td><p-skeleton></p-skeleton></td>
        <td><p-skeleton></p-skeleton></td>
        <td><p-skeleton></p-skeleton></td>
        <td><p-skeleton></p-skeleton></td>
      </ng-template>
    </tr>
  </ng-template>
</p-table>

Make sure to change the code as you need, this is just an example

Upvotes: 0

Related Questions