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?

1

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! You are a life saver!
I am glad I helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.