Convert an HTML table using p-table in PrimeNG version 7.x

I am working on an Angular application and using PrimeNG to create a table that displays the number of students by class. Currently, I have managed to set up a table with class names in one column and the number of students in another column. However, I need the data to be displayed with class names in rows and the number of students in separate rows. Is there a way to transpose the table while keeping the code clean?

Below is the HTML code for the table:

<p-table [value]="getData()">
    <ng-template pTemplate="header">
    </ng-template>
    <ng-template pTemplate="body" let-data>
        <tr>
            <td class="legend-cell" >
                {{data.className}}
            </td>
            <td class="non-edit-cell" >
                {{data.numStudents}}
            </td>
        </tr>
    </ng-template>
</p-table>

Here is the dummy data being used:

  getData(){
    let data = [];
    data.push({className: 'Class 1', numStudents: 22})
    data.push({className: 'Class 2', numStudents: 23})
    data.push({className: 'Class 3', numStudents: 24})

    return data;
  }

The current table layout can be seen in the image below:

https://i.sstatic.net/dK94r.png

However, I want it to look like this (manually edited image):

https://i.sstatic.net/5vo1b.png

Answer №1

Wow, I just discovered a really innovative approach. It's something I've never seen done with tables before:

Instead of only placing columns into rows, you can also put rows into columns:

<p-table [value]="getData()">
    <ng-template pTemplate="header">
    </ng-template>
    <ng-template pTemplate="body" let-data>
      <td>
        <tr>{{data.className}}</tr>
        <tr>{{data.numStudents}}</tr>
      </td>
    </ng-template>
</p-table>

What's even more fascinating is that you can achieve the same result without using rows at all by treating the first line as the header:

<p-table [value]="getData()">
    <ng-template pTemplate="header">
        <th *ngFor="let class of getData()">{{class.className}}</th>
    </ng-template>
    <ng-template pTemplate="body" let-data>
        <td>
            {{data.numStudents}}
        </td>
    </ng-template>
</p-table>

Answer №2

If you're looking to tackle this problem differently, consider using <div> along with CSS styles instead of relying on a table:

<p-table [value]="getData()">
    <ng-template pTemplate="body" let-data>
        <div style="display:inline-block;">
              {{data.className}}
          <div>{{data.numStudents}}</div>
        </div>
    </ng-template>
</p-table>

While Flex and other CSS properties could also be utilized, the above solution should suffice for your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

GeoChart : addListener :WARNING Error: The specified column index is invalid. It must be an integer between 0 and 1

When clicking on a country in Google GeoChart, I am attempting to retrieve the name of that country but encountering an error when using addListener. Explore my Stack Blitz demonstration here: https://stackblitz.com/edit/angular-advanced?embed=1&file= ...

Issue with Webpack throwing 'window undefined' persists despite using the 'use client' configuration in React/Next.js

I've been using Typescript 5, React 18, and Next.js 14 as my tech stack, and I keep encountering similar errors with various libraries. One of the errors I often face is ReferenceError: window is not defined. This error originates from a third-party ...

Whenever Ionic attempts to call an API using a Proxy, it consistently receives a

I am encountering an issue with accessing the API, where the URL consistently returns the External IP : http://192.168.**.**:8100 My API is hosted on a local IIS server with the IP address 192.168.**.**:3000 While debugging the project on the Android Emu ...

Guide to Making a Basic TypeScript Metadata Tag in Your Code

I'm looking for a way to format certain fields before sending them to the server-side. My goal is to serialize specific fields of my TypeScript classes using custom serializers. An example of what I'm aiming for is as follows: export class Pers ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

The implementation of a generic function interface in Typescript can pose a challenge

I've been working on incorporating a generic function interface, but I'm facing some challenges in getting it to function properly. IToken.ts export interface IToken { token: string; expires: number; } ITokenMapper.ts export interface ...

Incorporating a Symbol into a Function

Reviewing the following code snippet: namespace Add { type AddType = { (x: number, y: number): number; }; const add: AddType = (x: number, y: number) => { return x + y; }; } Can a 'unique symbol' be added to the AddType lik ...

"Although TypeOrm successfully generates the database, there seems to be a connectivity issue

Attempting to set up a JWT authentication system using NestJs and SQLite. The code successfully generates the SQLite file, but then throws an error stating "Unable to connect to the database." Upon checking with the SQLite terminal, it became apparent that ...

The Angular 4 iframe fails to show the content from the src link webpage

Template: <iframe width="100%" height="100%" [src]="url"></iframe> Component : I have successfully converted the URL into a safeUrl: ngOnInit() { this.url = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.google.com/ ...

Guide to routing within the same component in Angular?

In the scenario where I have multiple lists of users with IDs such as (1, 2, 3, 4, 5...), the desired functionality is that upon clicking a button, the details for each respective user should be displayed. For example, clicking on the first user's det ...

How come TypeScript doesn't recognize my MongoDB ObjectID as a valid type?

Currently, I am working with Node.js, MongoDB, and TypeScript. The code snippet below is error-free: const ObjectID = require("mongodb").ObjectID; const id = new ObjectID("5b681f5b61020f2d8ad4768d"); However, upon modifying the second line as follows: ...

Is there a way in TypeScript to specify that the parameters of an interface should be the keys of an object?

Here is the code I'm working with: interface IOrder { id: string created: string name: string age: number } type OrderKey = keyof IOrder const columnNames: OrderKey[] = ['id', 'name', 'age', 'created'] ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

When deleting a row, the pagination feature in <mat-table> may encounter issues with the sticky

Struggling with a problem that I couldn't find a solution for online, so hoping to get some help here. I'm currently working on a dynamically-filled table where users can delete individual rows. The table has a sticky column and pagination, but I ...

Issue with ngRX infinite loop caused by the updateOne function in the adapter

Hey there, I'm struggling to figure out why my code is stuck in an infinite loop. I've searched online extensively but haven't found a solution that fits my specific issue. This is the code snippet causing the problem: /** * CODE ...

Angular: Utilizing httpClient to retrieve an object map and passing it as a return value in a function

I have a basic Angular application that retrieves data from a Spring-Boot backend. export class UserDto { constructor( public login: string, public password: string, ) { } } export class AuthService { private url = '....'; get ...

What is the most effective way to retrieve the width and height of an oversized image in Angular?

After attempting to retrieve the image width using the ngAfterViewInit method, a result of width = 0 is returned due to the large size of the image. Is there a way to accurately determine the image width without relying on a setTimeout() function? For re ...

What is the best method for running a function before a modal window closes?

I am facing an issue with a modal housing a sign-up form in my Angular application. The problem arises when I try to close the modal using the data-dismiss attribute before sending the registration details to the server, causing the information not to regi ...