0

I am supplying a downloadable data to child through @input value. when user click on download link it's downloading the file without any issue.

But whenever there is a change going on and observed by ngOnchanges - triggers the download again and i am getting downloaded a unknown file. so, how to fix it or how can i make only it download the file on user click alone?

on user click i am triggering download event.

@Input() cpDownloadedFile: any;


initDownloadFile(fileData) {

    this.fileDownloaded.emit(fileData.Id);

}

ngOnChanges() {

      change1,

      change 2

       //other changes goes here

      if (this.cpDownloadedFile && changes.cpDownloadedFile) {
            const element = document.createElement('a');
            element.href = URL.createObjectURL(this.cpDownloadedFile);
            element.download = this.fileName.replace(/ /g, '').replace(/\_(?=[^_]*$).*(?=\.)/g, '');
            document.body.appendChild(element);
            element.click();
        }

}
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

1 Answers1

0

By what I understand from the given information, Even if the ngOnChanges is causing a file to download on change of other attributes, It should trigger the download of the last downloaded file. Are you sure the cpDownloadedFile is not changing elsewhere?

Try replacing the if condition to with the following,

if (this.cpDownloadedFile && changes.cpDownloadedFile &&
    changes.cpDownloadedFile.currentValue !== changes.cpDownloadedFile.previousValue )
    { /* download code */ }

Ref

Aakash More
  • 168
  • 1
  • 6
  • But it will not work. because as a first time after user trigger the event I am getting correct file get downloaded. after on wards getting some file without extension which is created the name by ash key. so each time the file would be new!! – 3gwebtrain Nov 28 '19 at 06:51
  • I didn't understand you. Can you please elaborate what happens the first time? – Aakash More Nov 29 '19 at 04:31