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

Leveraging req.files for uploading multiple files at once

When it comes to handling a multiple file upload on the client side, I have encountered an issue with my HTML code. Here is what it looks like: form(method='post', enctype='multipart/form-data')#createReportForm input(type='file ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

Follow the correct sequence when tapping the pipes and disregard the outcomes

I'm having trouble with executing tap functions in observables. In my scenario, I have a series of API requests that are dependent on each other. To handle this, I store the necessary data for the next request in class properties and use tap function ...

List with pulldown options

I am trying to implement a drop-down list with bullets using Angular 2, JavaScript, and CSS. Although I have managed to create the drop-down list, I am facing difficulty in adding bullets to the list items. Unfortunately, I have found that jQuery and Boot ...

Enhancing the performance of your code by optimizing it using jQuery when a checkbox is either checked or

Looking for ways to optimize a jquery function that toggles a URL parameter based on checkbox status. Any suggestions on how to streamline this code? $('#mapControl').live('click', function(){ var thisUrl = $(location).attr(' ...

Modify the state of a Babylon JS instance that was set up within an Angular 2 component

Hi there, I'm currently experimenting with injecting variables using Angular 2's Dependency Injection to alter the state of an object initialized within BabylonJS. I've tried using [(ngModel)]="Service.var" to access the variable and (ngMod ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...

Setting field names and values dynamically in MongoDB can be achieved by using variables to dynamically build the update query

I am working on a website where users can place ads, but since the ads can vary greatly in content, I need to be able to set the field name and field value based on user input. To achieve this, I am considering creating an array inside each document to sto ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

"Converting a standard grammar with recursion and alternations into a regular expression: A step-by-step

A grammar is considered regular if it follows either a right-linear or left-linear pattern. According to this tutorial, this type of grammar possesses a unique property: Regular grammars have a special characteristic: through the substitution of every no ...

Why is this method call not throwing an IndexOutOfBoundsException as expected?

I have created a basic function that takes a Date as an argument and determines whether it is winter or not, returning true or false, respectively. When I pass the "date" 2012-13-01 as an argument, I notice that the array does not have a 13th element. Des ...

Changing a List within a Structure

I have been working on a project for my coding class, specifically focusing on C#. I have a seemingly simple question that has left me puzzled as I cannot seem to find an answer anywhere. While searching, all I keep finding are results on how to create a l ...

How can I make a div's height match that of another div?

I am curious about adjusting the height of a div based on its content. In this case, I have the following HTML structure: div.Pantalla { background-image: url("https://cdn.pixabay.com/photo/2015/07/11/23/02/plane-841441_1280.jpg"); background-size ...

"Mix up the items from two ngFor loops for a dynamic display

My Angular project includes the following code: <app-red-elements *ngFor="let redElement of redElements" [element]="redElement"></app-video> <app-blue-elements *ngFor="let blueElement of blueElements" [element]="blueElement"></app-vid ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

JavaScript is throwing an error stating that the requestData is undefined, even though the

Hello, I am attempting to retrieve weather information based on the country and city using the openweather api. JSON is a new concept for me in coding, so please bear with me through this learning process. Below is the code snippet that I have been workin ...

Investigating sibling HTML elements using an Angular directive

When working with Angular 10, my goal is to access a sibling element within my directive. This is illustrated by the following code snippet: <label myDirective for="foo" ... <input id="foo" formControlName="xyz" ... Wit ...

Using TypeScript to incorporate JS web assembly into your project

I have been attempting to incorporate wasm-clingo into my TypeScript React project. I tried creating my own .d.ts file for the project: // wasm-clingo.d.ts declare module 'wasm-clingo' { export const Module: any; } and importing it like this: ...

When I click on the button, the output does not appear

Even though I know how to write this in pure javascript, I am new to angular so when I click submit, nothing happens and I don't get any result. index.html <input type="text" ng-model="username" placeholder="Username"> <input type=" ...

Communicating data between Angular components that have no direct binding or relationship

Struggling to transfer data between two unrelated components, anyone have advice on how to accomplish this? Here's an example: I have a page with 3 buttons that pass string values upon click to a variable named selectAgent. ~agents.html~ <div rou ...