oriaj
oriaj

Reputation: 788

get the value from a FileReader in Angular 2

I have the following component that load a file and bind his content as string

    export class NgCsvComponent {

        @Input() csv: any;

        @Output() csvChange: any = new EventEmitter();

        public localCsv : any = '';

      constructor() { }

      changeListener($event): void {
        this.readFile($event.target);
      }

      readFile (inputValue : any) : void {
        let reader = new FileReader (),
              file : File = inputValue.files[0];
          reader.readAsText(file);    
        reader.onload = this.onLoadCallback;
      }

        onLoadCallback (event) {
            this.csvChange.emit(event.target["result"]);
        }
    }

the problem is that this.csvChange is undefined inside onLoadCallback so how I could pass the result to some variable in my component?

I was search other similar question but never get the result outside of onloadCallback function

Upvotes: 2

Views: 4469

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71911

The problem is that the context is lost when you do:

reader.onload = this.onLoadCallback;

One solution is:

reader.onload = (e: Event) => {
    this.onLoadCallback(e);
}

Another one is:

reader.onload = this.onLoadCallback.bind(this);

Yet another one is:

onLoadCallback = (event) => {
    this.csvChange.emit((event.target as FileReader).result);
}

Bottom line. Make sure that the this context always remains inside your class.

Upvotes: 11

Related Questions