0

I have an issue where an array I initialise is then seen as undefined from within a function.

This is the code

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");

    }
  }
}

As you can see I initialise the array at the top of the class but then when I try to push to it in the onFileLoad function it is undefined. I can fix this by initialising the array in the function but this also results in the array not being updated in my view...

What am I doing wrong?

coolblue2000
  • 3,796
  • 10
  • 41
  • 62
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Feb 13 '19 at 22:43

1 Answers1

5

You have to set the context the function will use during invocation.

Try

  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.bind(this);  // <---- try this
      fileReader.readAsText(fileToRead,"UTF-8");

    }
  }

You can pass the event variable as well after defining the this context. bind(this, EVENT)

profanis
  • 2,741
  • 3
  • 39
  • 49