23

I am working on an angular2 project, I have a file in assets folder and I have created a button to download the file while running the app.

I see there are quite a many solutions to the above problem so i got confused. Can you please help.

<button pButton type="button" (click)="f1()" label="Download Sample Defaults 
XML File"></button>

I need code for f1() which can help me download the file to my Download folder when clicking on above button. Help appreciated. Thanks

Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Sunil Bishnoi
  • 509
  • 3
  • 5
  • 13

5 Answers5

30

You can either style an anchor element to look like a button and set it's href to assets/file

<a href="assets/file">Download here</a>

Or create an anchor element on the fly, set it's href element and click it.

Something like:

let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = 'assets/file';
link.download = path;
document.body.appendChild(link);
link.click();
link.remove();
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Carsten
  • 4,005
  • 21
  • 28
17

You don't need to change the template. Use this way

f1() {
    window.open('path', '_blank');
}

ex:

f1() {
   window.open('/assets/images/blabla.png', '_blank');
}

update

If you need to download file instead of opening a new tab use a link with html5 download attribute ex:

<a download="filename" target="_blank" href="/assets/images/blabla.png">
  Click here to download image
</a>
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
SFernando
  • 1,074
  • 10
  • 35
11

you can try this solution

ts file code

downloadFile(){
        let link = document.createElement("a");
        link.download = "filename";
        link.href = "assets/images/user-image.png";
        link.click();
}

html file code

<button (click)="downloadFile()">Download</button>
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
2

You can try this one. Put the file in assets and give the path in href.

<a class="iconsBG" title="Excel" href='/assets/Project-2021-05-17T10_41_22.378Z.xlsx' download="Project-2021-05-17T10_41_22.378Z.xlsx"><i class="far fa-file-excel"></i></a>
Josef
  • 2,869
  • 2
  • 22
  • 23
Amit Nayak
  • 41
  • 2
-2

This should work, short sweet and simple, the "download" and "#"-"yoclickme" makes it work

<a href="{{ this.fileurl }}" download #yoclickme></a> 
    <button (click)="yoclickme.click()"> Download </button>
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Gavin Chebor
  • 265
  • 3
  • 5