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

1 Answer 1

11

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.

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

3 Comments

Excellent implementation - particularly like the second solution. Thanks
I was trying to use event.target.result and always showed error until i changed it to event.target["result"]. Thank you!
@Akhil That's because event.target is typed as a EventTarget and this does not have the property result. You should cast it to FileReader first like: (event.target as FileReader).result

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.