Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API.
I followed a tutorial to retrieve the data from the CSV file on the Angular side and display it on the same page. However, I encountered the following error:
Type 'File | null' is not assignable to type 'File'. Type 'null' is not assignable to type 'File'.ts(2322)
I've tried multiple solutions but haven't been able to resolve it. Any help would be greatly appreciated!
Below is my .ts file:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styles: [
]
})
export class FileUploadComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
lines: any = [];
linesR: any = [];
changeListener(files: FileList) {
console.log(files);
if (files && files.length > 0) {
let file: File = files.item(0);
console.log(file.name);
console.log(file.size);
console.log(file.type);
let reader: FileReader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
let csv: any = reader.result;
let allTextLines = [];
allTextLines = csv.split(/\r|\n|\r/);
let headers = allTextLines[0].split(';');
let data = headers;
let tarr = [];
for (let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
this.lines.push(tarr);
let tarrR = [];
let arrl = allTextLines.length;
let rows = [];
for (let i = 1; i < arrl; i++) {
rows.push(allTextLines[i].split(';'));
}
for (let j = 0; j < arrl; j++) {
tarrR.push(rows[j]);
}
this.linesR.push(tarrR);
}
}
}
}
This is my .html file
<div class="container">
<h1 style="text-align: center"> File Upload </h1>
<br><br>
<input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)">
<table class="table table-bordered table-dark">
<thead>
<tr>
<th *ngFor="let item of lines[0]; let i = index">
{{item}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of linesR[0]; let i = index">
<td *ngFor="let itemm of lines[0]; let j = index">
{{item[j]}}
</td>
</tr>
</tbody>
</table>
</div>
Here is the error I encountered
Appreciate any assistance!