I'm trying to create a form that lets the user upload a csv file, which I will then manipulate using JS and return some arrays of objects. The issue is the upload part.
When I do it in vanilla JS, it works perfectly. But now I'm trying it in Angular and I get the following error:
ERROR TypeError: Cannot read properties of undefined (reading '0')
When I console.log() the pathname of the uploaded file, I get C:\fakepath\fileName.csv. This does not happen when using vanilla JS, so I suspect the issue might be related to that.
Below is my code:
home-page.component.html:
<div class="container">
<form #myForm id="myForm">
<div class="row">
<div class="col-10">
<label for="csvFile">Select CSV File</label>
<input class="form-control mb-3" type="file" accept=".csv" #csvFile />
</div>
<div class="col-2">
<!-- <button (click)="myClickFunction($event)" class= "btn btn-secondary mt-4" type="submit" value="Submit">Upload</button> -->
<input (click)="myClickFunction($event)" class="btn btn-secondary mt-4" type="submit" value="Upload" />
</div>
</div>
</form>
</div>
home-page.comomponent.ts:
import {Component, VERSION, ViewChild, ElementRef, OnInit} from "@angular/core";
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FormBuilder} from '@angular/forms';
import { NgModule} from '@angular/core';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
constructor() {}
ngOnInit(): void {}
@ViewChild('csvFile') csvFile!: ElementRef;
myClickFunction(event: any) {
event.preventDefault()
event.stopPropagation()
console.log(this.csvFile.nativeElement.value);
const input =this.csvFile.nativeElement.value.files[0];
const reader = new FileReader();
console.log("Form submitted " + input);
}
}
As I mentioned, I suspect the problem might be the fakepath file name, but I can't get sure. I'm very new to Angular so any help will be greatly appreciated! Thank you.