Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content.

For the header CSV file: header.csv

https://i.stack.imgur.com/ojMo6.png

For the table data CSV file: tableContent.csv

https://i.stack.imgur.com/kl6GF.png

I have successfully converted all the data into arrays. However, it is currently stored in a single array. Below is my code for better understanding. The .csv files are located in the assets folder.

app.component.ts

export class AppComponent {
  title = 'project';
  myData: any;
  myContent: any;
  constructor(private httpClient: HttpClient) { }
  ngOnInit() {
    this.httpClient.get('assets/header.csv', { responseType: 'text' }).subscribe(
      data => {
        this.myData = data.split("\n");
      }
    );
  }
  clicked(event) {
    console.log(event.srcElement.name);
    this.httpClient.get('assets/tableContent.csv', { responseType: 'text' }).subscribe(
      data => {
        this.myContent = data.split(",");
        let ab=this.myContent;
        console.log("------------>",ab);        
      }
    );
  }
}

app.component.html

<table id="customers">
  <tr>
    <th *ngFor="let dataheader of myData"><button (click)="clicked($event)" id={{dataheader}} name={{dataheader}}>{{dataheader}}</button></th>    
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
    <td>Germany</td>
  </tr>
</table>

Browser screen https://i.stack.imgur.com/elUo8.png

The goal is to create multiple object arrays as shown below:

[{
"myAccess":["myAccess","Prod","URL","[email protected]","Enable"]
},
{
"System":["System","Environment","URL","[email protected]","Enable"]
},
{
"OAM":["OAM","DEV","URL","[email protected]","Enable"]
},
{
"Mylogin":["Mylogin","prod","URL","[email protected]","Enable"]
}]

The table heading will come from the specific header.csv file, while the data will be sourced from the tableContent.csv file. When clicking on a particular header, it should search within the JSON object read from tablecontent.csv, displaying the corresponding result. For example, clicking on "myAccess" should display the related myaccess data in the table.

Thank you in advance, would appreciate your insights.

Answer №1

If you follow this solution, your issue should be resolved. It's important to handle errors more effectively than I did! 😄 (Styling with Bootstrap)

Component

import { Component, OnInit } from '@angular/core';
import { FileService } from './services/file.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  title = 'temp-app';

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

  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());
          }
        } else {
          this.headers = [];
        }
      }
    );

    this.fileSvc.getData().subscribe(
      data =>  {
        if (data != null && data.length > 0) {
          const tempData = data;
          let rows = [];
          rows = tempData.split('\n');
          for (let row of rows) {
            if (row.trim() === '') {
              continue;
            }
            row = row.replace('\r', '')
            const rowSplits = row.split(',');
            this.data[rowSplits[0]] = rowSplits;
          }
        } else {
          this.data = {};
        }
      });
  }

  headerSeleced(header) {
    this.selectedHeader = header;
  }
}

Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private httpClient: HttpClient) {

  }

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

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

Sample HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <h3>Headers</h3>
    </div>
    <div *ngFor="let item of headers"
      class="col-sm-3 bg-secondary p-2 m-1 text-white btn"
      (click)="headerSeleced(item)">
      {{item}}
    </div>
  </div>
  <hr>
  <div class="row">
    <ng-container *ngFor="let item of data | keyvalue">
      <ng-container *ngIf="selectedHeader == item.key" >
        <div class="col-auto border">
          <b>{{item.key}}</b>
        </div>
        <div *ngFor="let prop of item.value" class="col-auto border">
          {{prop}}
        </div>
      </ng-container>
    </ng-container>
  </div>
</div>

Answer №2

class NewAppComponent {
  appTitle = 'new project';
  data: any;
  content = [];
  
  constructor(private httpService: HttpClient) { }
  
  initialize() {
    this.httpService.get('assets/info.csv', { responseType: 'text' }).subscribe(
      response => {
        this.data = response.split("\n");
      }
    );
  }

  handleEvent(event) {
    console.log(event.srcElement.name);
    
    this.httpService.get('assets/content.csv', { responseType: 'text' }).subscribe(
      result => {
        this.content.push({event.srcElement.name: result.split(",")});
        let updatedContent=this.content;
        console.log("Updated Content:", updatedContent);        
      }
    );
  }
}

Answer №3

To remove the next line icon, follow these steps:
https://i.stack.imgur.com/GBMy4.png

Add the following code in your app.component.ts file:

this.httpClient.get('assets/content.csv', { responseType: 'text' }).subscribe(
      data => {
             // insert this line before splitting
              data = data.replace(/[\r\n]/g,",");
             this.headerData = data.split(",").filter(Boolean);
      }
    );

First, extract the header data from a CSV file:

this.httpClient.get('assets/header.csv', { responseType: 'text' }).subscribe(
      data => {
             // insert this line before splitting
              data = data.replace(/[\r\n]/g,",");
             this.headerData = data.split(",").filter(Boolean);
      }
    );

To achieve the desired result, adjust the array based on the length of this.headerData.
Based on the image in your CSV file, the column length will be dynamic according to this.headerData.length

 for( let index = 0; index < this.myContent.length; index ++) {
           const value = this.myContent.splice(0,this.headerData.length);
          // now you can structure the data as needed
 }


For more information on how to use Array.Splice() to create sub-arrays.

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

Tips for sending information from an AJAX request to a Laravel 5.2 controller using the POST method

Hello everyone. I'm reaching out to the great community for some assistance with my first question here. I've recently started working with Laravel framework version 5.2 in a project of mine. My issue lies in trying to pass data using the post m ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Searching for multiple filtered items in Vue.js

When working with Vue js, searching through a list is straightforward. However, when dealing with a large dataset of 1000 records and needing to apply specific filters for user searches, I find myself at a loss. Is there a plugin or method that can help me ...

struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills: function tank(){ this.width = 50; this.length = 70; } function Person(job) { this.job = job; this.married = true; } var tank1 = tank(); console.log( ...

Strategies for managing various errors that can arise when multiple Angular components are subscribed to a single state

My Angular application is facing a dilemma with three components at play: Component #1: Shows a list of items Component #2: Displays recently used items Component #3: Exhibits the current item For now, let's assume they're all visible on the sa ...

Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing this scri ...

Determine changes in data retrieved from a JSON file using React

I've been working on a cryptocurrency app using React and a JSON API to fetch the latest data. My approach involves using fetch to load the JSON API and setInterval to refresh the app every 10 seconds. Now, I'm wondering if there's a way to ...

various positions for ngb properties

My input field has both a tooltip and a dropdown attached to it using the ngb attributes: <input placement="right" ngbTooltip="Search" [ngbTypeahead]="search" /> The issue I'm facing is that I want the tooltip to appear on the right ...

Using ReactJS to compare arrays and render only if the name is present in both arrays

Currently, I am developing a Star Wars web application using ReactJS. The data is being retrieved from the SWAPI (an API that provides JSON data about Star Wars). While everything is functional, I want more control over which characters are displayed. At t ...

Encountering compilation errors with Angular project following installation of a package

I recently installed the LocalStorage Package and encountered the following message: npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

Enhancing code completion with IntelliSense for customized styled components' themes

When using a theme in styled components, I am attempting to enable IntelliSense. In my code snippet below (index.tsx), I utilize ThemeProvider: import React from 'react'; import ReactDOM from 'react-dom/client'; import { ThemeProvider } ...

What is the best way to retrieve the dimensions of a custom pop-up window from the user?

Currently, I am in the process of developing a website that allows users to input width and height parameters within an HTML file. The idea is to use JavaScript to take these user inputs and generate a pop-up window of a custom size based on the values pro ...

Looking for a particular value within a multidimensional $_SESSION array - here's how!

In my coding project, I am utilizing a $_SESSION array to keep track of item details such as description, quantity, and price for items added to a shopping cart. The initial part of the code functions smoothly, as shown below: $quantity = 1; // add first ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...

Issue with starting Angular2 beta 15 using npm command

I am encountering a problem when trying to launch the quick start application for Angular2. node -v 5.10.1 npm -v 3.8.6 My operating system is EL CAPTAIN on MAC OS X. This is my tsconfig.json file: { "compilerOptions": { "target": "es5", "mo ...

Exporting JSON data as an Excel file in AngularJS, including the option to customize the fonts used for the

Currently, I am working on a project where I need to convert JSON data to an Excel file using JavaScript in combination with AngularJS. So far, I have successfully converted the JSON data to CSV format. However, I faced issues with maintaining the font s ...

I recently made the switch to Angular 9.0 for my project, but when I ran the build using yarn, I encountered some warnings. Despite the

I encountered this issue on both Ubuntu 16.04 and 18. I have tried various solutions such as reinstalling yarn, node, and clearing the cache, but the warnings persist. For every build using a script, the node_modules folder is deleted and then reinstalled ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

How to submit a form in Angular2 without reloading the page

I have a straightforward form to transmit data to my component without refreshing the page. I've tried to override the submit function by using "return false," but it doesn't work as expected, and the page still refreshes. Here is the HTML: ...