DnyaneshSurya
DnyaneshSurya

Reputation: 207

upload json file and read it in angualr 8

Below is my code but I am getting undefined :

onChange(fileList: FileList): void {
    var file = fileList[0];
    var fileReader = new FileReader();
    var newFile = {};
    fileReader.readAsText(file, 'UTF-8');
    fileReader.onload = () => {
      newFile = fileReader.result as object;
      this.updateObj = cloneDeep(newFile);
    };
    console.log('updateObj', this.updateObj);
}

I want to upload json file (ARM template)and read it but in console.log this.updateObj is showing undefined.

Upvotes: 0

Views: 216

Answers (1)

peinearydevelopment
peinearydevelopment

Reputation: 11464

It is very unclear as to what you are asking. I think this should answer your question though.

In the future, creating an MRE will make it much easier for others to help you.

.ts

  updateObj: any;
  onChange(event: any): void {
    var file = event.target.files[0];
    var fileReader = new FileReader();
    fileReader.readAsText(file, "UTF-8");
    fileReader.onload = () => {
      const newFile = fileReader.result as string;
      this.updateObj = JSON.parse(newFile);
    };
  }

.html

<input type="file" (change)="onChange($event)" />

<pre><code>{{updateObj | json}}</code></pre>

Stackblitz is a wonderful tool to user for creating MRE's for an Angular question.

Stackblitz example

UPDATE

@DnyaneshSurya Thank you for the MRE. Your example is working, but it still isn't clear what you want to do. ngOnInit is only called once when the component is initialized. The value for your Input at that time is undefined. That won't change as the ngOnInit method is only called once. Your variable armTemplate is getting updated though, as can be seen if you would update your hello component template to be <h1>{{armTemplate | json}}</h1>. If you want to perform some action when that value gets updated though, then the easiest way would be to use the getter/setter on your armTemplate property.

Here is another Stackblitz example to demonstrate.

Upvotes: 3

Related Questions