How to populate data on UI after reading from CSV file in Angular?

大憨熊 提交于 2020-06-01 04:46:27

问题


I am implementing angular template and I am reading CSV file data to show it in an organized table. I am not strong at core scripting part based on retrieved csv data.

I am sharing 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' });
  }

}

Above code is not correct: I am sharing UI, What I am accepting.

data.csv

Expected
1. Code first should read the column 1 i.e "AppName" and after reading all the rows of column 1 it should only keep the unique values and create a button using those unique values.Means - if "LDAP" is multiple times in column 1, it should only consider "LDAP" only once and using that it should create a button. 2. Similarily, create button for all remaining values of column 1.

For reference purpose one related link here:

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

Thanks in advance In future I want to show respective value only in column. If i click on OAM then OAM column will show, If I will click on LDAP the LDAP column value will show.


回答1:


lets say you are getting this data from assets folder. For eg :-

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;
}));

When you will subscribe to it you will get a object like below :-

{
  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 the above data structure you can easily create your template using ngfor directive.

Eg:- 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
  }
}
}


来源:https://stackoverflow.com/questions/62113680/how-to-populate-data-on-ui-after-reading-from-csv-file-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!