6

I am unable to find the answer anywhere, hopefully someone can help.

I have an Angular2 click event defined in the template, inside the table's cell:

<td (click)="click2Download()">fileName.txt</td>

In the typescript component, I need help to define a method click2Download() that would automatically start downloading the fileName.txt to client's browser. Note: file is on the same domain, e.g.:

http://example.com/fileName.txt

Any way of doing this with Angular2?

jjj
  • 2,594
  • 7
  • 36
  • 57
  • Possible duplicate of [Angular 2 download PDF from API and Display it in View](http://stackoverflow.com/questions/35368633/angular-2-download-pdf-from-api-and-display-it-in-view) – Fiddles Nov 02 '16 at 02:28

1 Answers1

7

Have you tried: window.location.href = '...'; ?

To force download of files you should use html attribute: <a target="_self" href="somefile.txt" download="somefile.txt">

spa900
  • 927
  • 9
  • 19
  • Thanks for trying to help. I just tried it and while that works nicely for zip files, it doesn't work for text files. It redirects users to url of the text file instead of downloading the file. – jjj Nov 02 '16 at 00:50
  • 1
    Forcing it to download can be done by using the HTML download attribute: http://www.w3schools.com/tags/att_a_download.asp or by forcing a download by changing headers via .htaccess file. – spa900 Nov 02 '16 at 00:53
  • 1
    Yes, that works, but I need to do this inside typescript method, as there is some other processing (getting file name, etc.) happening before I start the download... – jjj Nov 02 '16 at 00:58
  • Try to specify this in your question next time. You'll find what you need here: http://stackoverflow.com/a/28541187/1003577 – spa900 Nov 02 '16 at 01:00
  • That is how it was done in Angular1, do you know a way of doing this in Angular2? – jjj Nov 02 '16 at 01:03
  • that unfortunately requires a third party library and it just generally seems like an outdated way of achieving a goal, from the time when Angular2 used to be in alpha/beta stage... – jjj Nov 02 '16 at 15:37