What is the best method for displaying data on the user interface in Angular after retrieving it from a CSV file

I am currently working on implementing an Angular template where I need to display data from a CSV file in a structured table format. However, I am facing challenges with the core scripting part related to the retrieved CSV data.

Here is a snippet of my code:

export class AppComponent implements OnInit{
  title = 'temp-app';

  public headers = [];
  public data = {};
  public strData = ''

  public selectedHeader = null;
  constructor(private fileSvc: FileService) {

  }

  ngOnInit(): void {
    this.fileSvc.getHeaders().subscribe(
      data => {
        if (data != null && data.length > 0) {
          let headers = data.split('\n');
          headers = headers.filter(x => x.trim() !== '');
          for (const item of headers) {
            this.headers.push(item.trim());
          }
          this.headers=[...new Set(this.headers)];         
        } else {
          this.headers = [];
        }
      }
    );

Service.ts

@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(private httpClient: HttpClient) {

  }

  public getHeaders() {
    return this.httpClient.get('assets/data.csv', { responseType: 'text' });
  }

}

The code above needs some corrections. Here is the UI design I am aiming for: https://i.sstatic.net/CACLZ.png

data.csv
https://i.sstatic.net/OSbFz.png

Expected behavior:
1. The code should read the first column "AppName" and extract unique values from all the rows in that column. Using these unique values, buttons should be created. For example, if "LDAP" appears multiple times in the column, it should only be considered once for creating a button. 2. Repeat the process to create buttons for all other values in the first column.

For reference:

https://stackblitz.com/edit/angular-ivy-ubcknl

Thank you in advance. In the future, I plan to enhance the functionality to display only the respective column values when a button is clicked. For example, clicking on OAM will display the OAM column values, and clicking on LDAP will show the LDAP column values.

Answer №1

Imagine you are fetching data from the assets folder. For example:

return this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).pipe((map(res)=> {
                       let columns= new Set(response.split('\n').map((item) => item.replace('\r', '').split(",")[0]));
                       let rows= response.split('\n'); 
                       let result obj = {
                                             uniqueColumns: Array.from(columns),
                                             data: {}
                                        }
                       columns.forEach((columnName) => {
                           obj.data['columnName'] = [];
                       });
                       rows.forEach((row) => {
                              var rowItems = row.replace('\r', '').split(",");
                              obj.data[rowItems[0]].push(rowItems.slice(1));
                       });
                       return obj;
}));

Upon subscription, you will receive an object structured like this:

{
  uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
  data: {
      'OAM': [
         ['DEV', 'OHS', 'Success'],
         ['Stage', 'OHS', 'Success']
       ],
       'LDAP': [
         ['DEV','MDS','FAIL'],
         ['DEV','DDNET','FAIL']
         //and other data
       ]
       //same for other columns
  }
}

With this data structure, you can easily create a template using the ngfor directive.

Example Template Code:

<table id="mainTable">
  <thead>
    <tr>
      <th *ngFor="let head of items.uniqueColumns">{{head}}</th>
    <tr>
  </thead>
  <tbody> 
    <tr>
      <td *ngFor="let head of items.uniqueColumns">
        <table id="columns">
          <tr>
            <td></td>
            <td *ngFor="let col of items.data[head]">
              <ng-container *ngFor="let items of col">
                  <td >{{items}}</td>
              </ng-container>
            </td>
          <tr>
          <tr>
            <td>Dev</td>
          </tr>
          <tr>
            <td>Stage</td>
          </tr>
        </table>
      </td>
    </tr>
  </tbody>
</table>

CSS:

table#mainTable,table#columns, th {
  border: 1px solid black;
}
#columns td {
  padding: 1em;
}
#columns>tr>td:not(:first-child) {
  border: 1px solid black;
}
#columns>tr>td:nth-child(2) {
  border-left: none;
}

#columns>tr:nth-child(1) {
  border-bottom: 1px solid black;
}
tr {
  padding: 1em;
}

table, td, th {
  border-collapse: collapse;
}

Typescript:

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public items = {
  uniqueColumns: ['OAM','LDAP', 'myAccess', 'OAM', 'myLogin'],
  data: {
      'OAM': [
         ['DEV', 'OHS', 'Success'],
         ['Stage', 'OHS', 'Success']
       ],
       'LDAP': [
         ['DEV','MDS','FAIL'],
         ['DEV','DDNET','FAIL']
         //and other data
       ]
       //same for other columns
  }
}
}

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

Utilizing ng-change in an AngularJS directive with isolated scope to transition towards a component-based architecture. Let's evolve our approach

I've been struggling to get ng-change to trigger in my directive with an isolated scope. I'm working on transitioning from ng-controller to a more component-based architecture, but it's turning out to be more difficult than I anticipated. I ...

Deployment replacement in Kubernetes encounters error

I've developed a NodeJS script to deploy review apps to Kubernetes for my GitLab repository, using the Kubernetes NodeJS client. Including abbreviated definitions of Kubernetes resources for thoroughness: const k8s = require('@kubernetes/client ...

Tips for packaging NPM packages from the local directory

Hey there! I recently downloaded an npm module from GitHub and made some changes to it. Now, I am trying to install it locally using `npm install`, but the files are not being compiled and I am still seeing .ts instead of .js files. I have tried following ...

Highlight text when hovered over after a delay of X seconds

I have a question about implementing a feature where when a user hovers over any word in a text for two seconds, it will automatically become underlined. If the user clicks on the word, it will remain underlined until they click outside of the text or cl ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...

Why does Drupal's Advagg display several css and js files?

After installing the Advag module, I noticed that it is combining files, but there seems to be an issue: <link type="text/css" rel="stylesheet" href="/sites/default/files/advagg_css/css__sqX0oV0PzZnon4-v--YUWKBX0MY_EglamExp-1FI654__IOPiOtulrIZqqAM0BdQC ...

Identifying the mobile browser initiating the request call

I'm in the process of creating a website that needs to be compatible with various devices such as iPhone, Android, Samsung Galaxy S/S2, iPad, Samsung Galaxy Tab, and more. Is there a method to identify the mobile browser requesting the page and apply ...

The vertical scroll position of a container with overflowing content does not correspond to the height of its elements

I have a div that has a fixed height of 155px and is set to scroll vertically when overflow occurs. Inside this div, there is an unordered list with a height of 338px. I am attempting to determine when a user reaches the bottom of that div. $('.myD ...

Setting the backEnd URL in a frontEnd React application: Best practices for integration

Hey there - I'm new to react and front-end development in general. I recently created a RESTful API using Java, and now I'm wondering what the best way is to specify the backend URL for the fetch() function within a .jsx file in react. Currently, ...

Guide on extracting a parameter from a response URL using Angular (Stripe Connect)

To initiate the setup process for Stripe Connect's standalone account, the first crucial step is obtaining the user's permission in order to establish the connection. This initial interaction can be facilitated by directing the user to the follo ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

Using jqGrid to load additional JSON data after the initial local data has already been populated in the

I encountered a specific issue: I have a compact form with four choices. Users can choose to fill them out or not, and upon clicking 'Ok', a jqGrid is loaded with data based on those selections. To accommodate dynamic column formatting, my servle ...

What sets apart the browser/tab close event from the refresh event?

Can you help me understand the difference between a browser/tab close event and a refresh event? I've been researching this on Stack Overflow, but I'm still having trouble with it. My goal is to be able to log out a user through a server call whe ...

What is the best way to mix up the images in my memory game?

My JavaScript memory game is functioning properly, but I would like the images to load in a random order. Unfortunately, I'm not sure how to accomplish this. Here is the current setup: var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", " ...

Node.js and Express experiencing issues with updating cookies functionality

After successfully logging in, I created a login cookie. However, when I attempted to update the data within that cookie, an error occurred: Can't set headers after they are sent. Below is the code snippet in question: /* Logout to main user. */ /* ...

How to dynamically insert a hyperlink inside a <td> element within a table using JavaScript

What is the best way to create a hyperlink in a <td> within a dynamic table? I want the first <td> to be a link that combines a URL with the cell value. This is how the dynamic table is created: for (var i = 0; i < riskData.length; i++) { ...

What is the process of transforming a Firebase Query Snapshot into a new object?

Within this method, I am accessing a document from a Firebase collection. I have successfully identified the necessary values to be returned when getUserByUserId() is invoked, but now I require these values to be structured within a User object: getUserB ...

Encountering an error with Angular-NG8001 due to an unknown element. Any suggestions on how

I am encountering an issue with my Angular project. The project structure I am working with can be found here: app structure. Within my app.module.ts file, the code appears as follows: import { NgModule } from '@angular/core'; import { BrowserMod ...

Accessing and displaying all states in $stateProvider using AngularJS and ui-router

Here's a simple question: how can I find all instances of $stateProvider.state in my app.js, which is my AngularJS config file? In the past with ngRoute, I could achieve this by using a similar approach in my .run() block: .run(function ($route) { ...

A guide to selecting the dropdown item labeled as (Select All) using Python and Selenium

edit: Trying to submit parameters for a database-generated report on this page. Successfully modified the start date in the first field using send_keys(), but unable to click on "(Select All)" for fields 3 and onwards, except one. In order to access the h ...