Encountering an issue where an array I initiate is suddenly undefined within a function.
Here is the code snippet:
import { Component, OnInit } from '@angular/core';
import { text } from '@angular/core/src/render3';
import{SheetModel} from './models/sheetModel';
import { ThrowStmt } from '@angular/compiler';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'AngularCSVTest';
csvContent: string;
detailItems:SheetModel[]=[];
ngOnInit(){
}
onFileLoad(fileLoadedEvent)
{
//this.detailItems=[];
const textFromFileLoaded=fileLoadedEvent.target.result;
this.csvContent=textFromFileLoaded;
var rows=this.csvContent.split('\n');
for(var i:number=0;i<rows.length;i++)
{
var item=new SheetModel();
var rowItems:string[];
rowItems=rows[i].split(",");
item.index=i+1;
item.Make=rowItems[0];
item.Model=rowItems[1];
item.Colour=rowItems[2];
this.detailItems.push(item);
}
this.detailItems = this.detailItems.slice();
}
onFileSelect(input: HTMLInputElement) {
const files=input.files;
var content=this.csvContent;
if(files && files.length)
{
const fileToRead=files[0];
const fileReader=new FileReader();
fileReader.onload=this.onFileLoad;
fileReader.readAsText(fileToRead,"UTF-8");
}
}
}
Upon analysis, it seems that initializing the array at the beginning of the class results in it being undefined when attempting to push values to it within the onFileLoad function. One workaround could be initializing the array within the function, but this may lead to the array not updating in the view...
Seeking guidance on resolving this issue. Any insights are appreciated.