How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used.

The data obtained from the server (via C# web API) is structured like this:

[
   {
      "code":"0001",
      "commissionId":"something",
      "commissionType":0,
      "description":"Some Description",
      "registrationList":[
         {
            "activityCode":"01.6",
            "activityDescription":"Desc1",
            "activityId":"ActivityId1",
            "minuteWorked":120
         }
         // ...
         // Additional data may follow the same format
      ]
   }
   // ...
   // Additional data may follow the same format
]

In the initial array, there can be multiple commission entries, each containing various elements within the registrationList.

To achieve this, I aim to:

  • Show the commission code in the first column, which remains fixed (I know how to do this)
  • Display the registration list in the table data, matching the activityCode found in the table header (this part I am uncertain about)

Table Preview


I attempted to utilize *ngIf and *ngFor to iterate through the initial array and then further loop through the registrationList. However, this approach was not successful.

The <th> values are generated based on looping through an activityList.Here's a snippet of my code that reflects this structure:

<thead>
  <tr>
    <th>Commission</th>
    <th *ngFor="let activity of activityList" class="text-center">{{activity.code}}</th>
  </tr>
</thead>

<tbody>
  <tr *ngFor="let data of serverData index as i">
    <td nzLeft>{{data?.code}} - {{data?.description}}</td>
    <ng-container *ngFor="let activity of activityList">
      <ng-container *ngFor="let r of serverData.registrationList">
        <td *ngIf="r.activityCode == activity?.code; else noData">{{data.description}} - {{r.activityCode}}
          <td #noData> no data </td>
      </ng-container>
    </ng-container>
  </tr>
</tbody>

If anyone has insights or suggestions on how to address this issue, your guidance would be greatly appreciated. Thank you!

Answer №1

It seems that your issue lies not on the frontend side. The key here is to properly format the data before displaying it in the front end. Allow me to elaborate:

  • Typically, it's recommended to delegate high-demanding tasks to the backend. The role of the front end (Angular) is primarily for presentation purposes, although it has the capability to do more. However, utilizing an *ngFor loop as you have done may not be the most efficient approach.

To format the data on the backend server, follow these steps:

  • Create a class to represent individual cells.
  • Create another class to represent a row (which consists of a list of cells).
  • Lastly, create a class to encompass the entire table structure (with a header containing one row and a body consisting of multiple rows).

PivotCelViewModel.cs

public class PivotCelViewModel
    {
        public string Content { get; set; }
    }

PivotRowViewModel.cs

public class PivotRowViewModel
    {
        public PivotRowViewModel()
        {
            CellList= new List<PivotCelViewModel>();
        }

        public List<PivotCelViewModel>  CellList { get; set; }
    }

PivotViewModel.cs

 public class PivotViewModel
    {
        public PivotViewModel()
        {
            TBody = new List<PivotRowViewModel>();
        }
        public PivotRowViewModel THead { get; set; }
        public List<PivotRowViewModel> TBody { get; set; }
    }

In PivotRowViewModel.cs, I have added a constructor to ensure proper instantiation of a new list each time. This helps prevent errors when creating objects of that class.

Subsequently, populate these classes with data so that on the front end, you can easily iterate over the formatted data without requiring additional logic.

I hope this explanation proves helpful. Best of luck!

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

What is a way to perform pre-increment without utilizing the ++I operator?

It is my belief that the code snippet below: i += 1 or i = i + 1 does not have the same effect as ++i. Am I incorrect in this assumption? Is there an alternative method to achieve pre-increment without utilizing the ++ operator? ...

What is the best way to incorporate a sliding effect into my cookie form?

I created a cookie consent form for my website and I'm looking to include a sliding effect when it first appears and when it disappears after the button is clicked. How can I implement this sliding effect into the form? Here's the HTML, CSS, and ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

The email validation function is not functioning correctly when used in conjunction with the form submission

I'm currently working on my final project for my JavaScript class. I've run into a bit of a roadblock and could use some guidance. I am trying to capture input (all code must be done in JS) for an email address and validate it. If the email is va ...

Implementing uniform column width in a Material-UI Grid

Looking for a way to create a single column layout with items of equal width using the Material-UI Grid system? Check out this sample code: <Grid container align="center" direction="column"> <Grid item className={classes.item}> < ...

Compiling a list of products, but the user interface needs some adjustments

Currently, I have designed a product list menu that includes a hover dropdown feature. This means that when a user hovers over a specific menu item, the corresponding list will automatically appear. However, I am facing two issues with this setup. Firstly, ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Alignment problem with email signatures on MAC devices

Recently, I designed a straightforward email signature and successfully copied and pasted it into the appropriate section. However, while it works perfectly in Outlook, there is an issue with MAC Mail (Version 7.3) where the image extends beyond the table. ...

Can someone explain the function of statements such as (function () { // code; }.call(this)); within a JavaScript module?

By utilizing the Function.prototype.call() method, it becomes possible to create a function that can be applied to various objects. I delved into the code of , which had been minified and required to be un-minified for examination. The structure of the co ...

Defining RefObject effectively in TypeScript

Greetings everyone, I am a newcomer to TypeScript and currently attempting to create a type for a RefObject that is of type HTMLAudioElement. However, I have encountered an error message. The error states: Type 'MutableRefObject<HTMLAudioElement> ...

When utilizing the `express.static(__dirname)` function in Node.js with Express, the visitor may be directed to an incorrect HTML page

My website consists of a login page named login.html and an index page named index.html. I want to implement authentication so that only logged in users can access the index page. I have not set up the post method on the login HTML page. Therefore, I have ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

What allows mapped types to yield primitive outputs when using {[P in keyof T]}?

Check out this innovative mapped type example that utilizes the power of keyof: type Identity<T> = { [P in keyof T]: T[P]; }; Have you ever wondered why Identity<number> results in the primitive number type, rather than an object type? Is th ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...