简体   繁体   English

如何在 angular 中上传 csv 文件 13 错误:“my-app”

[英]How to upload csv file in angular 13 Error:"my-app"

I am studying angular.我正在研究 angular。

I created a csv file to upload with the following source code, The screen is completely blank with nothing displayed.我创建了一个 csv 文件以使用以下源代码上传,屏幕完全空白,没有任何显示。

nothing displayed is blank没有显示是空白的

Is it not displayed depending on the version?根据版本不显示吗?

Reference URL参考URL

Angular Upload Readcsv | Angular 上传Readcsv | stackblitz 堆栈闪电战

Read CSV and convert JSON Data in Angular 读取 CSV 并转换 Angular 中的 JSON 数据

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 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 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 app.component.css

p {
  font-family: Lato;
}
.table,.container{
  margin-top:20px; 
}
.btn{
  margin-right:20px; 
  margin-top: 20px;
}
<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);
}

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.或者再次运行npm i以确保应用最新的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM