0

I am studying angular.

I created a csv file to upload with the following source code, The screen is completely blank with nothing displayed.

nothing displayed is blank

Is it not displayed depending on the version?

Reference URL

Angular Upload Readcsv | stackblitz

Read CSV and convert JSON Data in Angular

Console error

ERROR Error: The selector "my-app" did not match any elements
    at DefaultDomRenderer2.selectRootElement (platform-browser.mjs:580:19)
    at locateHostElement (core.mjs:9830:1)
    at ComponentFactory.create (core.mjs:21603:1)
    at ApplicationRef.bootstrap (core.mjs:26538:1)
    at core.mjs:26219:1
    at Array.forEach (<anonymous>)
    at PlatformRef._moduleDoBootstrap (core.mjs:26219:1)
    at core.mjs:26189:1
    at _ZoneDelegate.invoke (zone.js:372:1)
    at Object.onInvoke (core.mjs:25608:1)

app.component.ts

/*
https://www.eduforbetterment.com/
*/
import { Component, VERSION, ViewChild } from '@angular/core';

export class CsvData {
    public id: any;
    public min: any;
    public max: any;
    public score: any;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  public records: any[] = [];
  @ViewChild('csvReader') csvReader: any;
  jsondatadisplay:any;

  uploadListener($event: any): void {

    let text = [];
    let files = $event.srcElement.files;

    if (this.isValidCSVFile(files[0])) {

      let input = $event.target;
      let reader = new FileReader();
      reader.readAsText(input.files[0]);

      reader.onload = () => {
        let csvData = reader.result;
        let csvRecordsArray = (<string>csvData).split(/\r\n|\n/);

        let headersRow = this.getHeaderArray(csvRecordsArray);

        this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);
      };

      reader.onerror = function () {
        console.log('error is occured while reading file!');
      };

    } else {
      alert("Please import valid .csv file.");
      this.fileReset();
    }
  }

  getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {
    let csvArr = [];

    for (let i = 1; i < csvRecordsArray.length; i++) {
      let curruntRecord = (<string>csvRecordsArray[i]).split(',');
      if (curruntRecord.length == headerLength) {
        let csvRecord: CsvData = new CsvData();
        csvRecord.id = curruntRecord[0].trim();
        csvRecord.min = curruntRecord[1].trim();
        csvRecord.max = curruntRecord[2].trim();
        csvRecord.score = curruntRecord[3].trim();
        csvArr.push(csvRecord);
      }
    }
    return csvArr;
  }

//check etension
  isValidCSVFile(file: any) {
    return file.name.endsWith(".csv");
  }

  getHeaderArray(csvRecordsArr: any) {
    let headers = (<string>csvRecordsArr[0]).split(',');
    let headerArray = [];
    for (let j = 0; j < headers.length; j++) {
      headerArray.push(headers[j]);
    }
    return headerArray;
  }

  fileReset() {
    this.csvReader.nativeElement.value = "";
    this.records = [];
    this.jsondatadisplay = '';
  }

  getJsonData(){
    this.jsondatadisplay = JSON.stringify(this.records);
  }


}

app.component.html

<div class="container">

  <div class="card">
    <div class="card-header">
      Upload csv to read
    </div>
    <div class="card-body">

      <input type="file" #csvReader name="Upload CSV" id="txtFileUpload" (change)="uploadListener($event)"
        accept=".csv" />

    </div>
  </div>

  <a href="javascript:;" *ngIf="records.length > 0" (click)="getJsonData()" class="btn btn-primary">Convert Json </a>

  <a href="javascript:;" *ngIf="records.length > 0" (click)="fileReset()" class="btn btn-primary">Reset </a>

  {{jsondatadisplay}}
  <table class="table" *ngIf="records.length > 0">
    <thead class="thead-dark">
      <tr>
        <th scope="col">#</th>
        <th scope="col">Min</th>
        <th scope="col">Max</th>
        <th scope="col">Score</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let record of records;let i = index;">
        <th scope="row">{{record.id}}</th>
        <td>{{record.min}}</td>
        <td>{{record.max}}</td>
        <td>{{record.score}}</td>
      </tr>

    </tbody>
  </table>
</div>

app.component.css

p {
  font-family: Lato;
}
.table,.container{
  margin-top:20px; 
}
.btn{
  margin-right:20px; 
  margin-top: 20px;
}
0

2 Answers 2

1
<button (click) = "downloadCSV()" > Download CSV</button >

    status: any[];
formula: string = "Formula 1";
downloadCSV() {
    this.status = ["approved", "rejected", "pending"];
    var data = [
        {
            name: "Test 1",
            age: 13,
            average: 8.2,
            status: this.status[0],
            description: "Kuala Lmpuer, Malaysia"
        },
        {
            name: 'Test 2',
            age: 11,
            average: 8.2,
            status: this.status[1],
            description: "Jakarta, Indonesia"
        },
        {
            name: 'Test 3',
            age: 10,
            average: 8.2,
            status: this.status[2],
            description: "Bangkok, Thailand"
        },
    ];

    var options = {
        title: 'User Details',
        fieldSeparator: ',',
        quoteStrings: '"',
        decimalseparator: '.',
        showLabels: true,
        showTitle: true,
        useBom: true,
        headers: ['Name', 'Age', 'Average', 'Status', 'Address']
    }; `enter code here`

    new Angular2Csv(data, this.formula, options);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Please check again the console in your browser to check the error.

This is an image in my local when applying your code

Or run again npm i to make sure to apply the newest lib.

3 Comments

Thanks for the comment but I don't get any errors. And I also tried npm i but I still get the white screen.
Sorry I found an Error: The selector "my-app" did not match any element
Yeah, enjoy it. Good luck,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.