I need to use the FileSaver.js (https://github.com/eligrey/FileSaver.js/) in my Angular2 application.
I know I can add it as a script file in main html page and it will work. But I was wondering what would be the best approach in case of an Angular 2 (TypeScript) application so that I can just call window.saveAs to save file.
Basic usage Include ngFileSaver module into your project; Pass both FileSaver and Blob services as dependencies; Create a Blob object by passing an array with data as the first argument and an object with set of options as the second one: new Blob(['text'], { type: 'text/plain;charset=utf-8' }) ; Invoke FileSaver.
FileSaver. js is the solution to saving files on the client-side, and is perfect for web apps that generates files on the client, However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatiblity.
You can npm install file-saver, then point to the node_modules FileSaver. js file in the <script> tag. Save this answer. Show activity on this post.
The File Saver component enables you to save files on the client machine. The saving of files is done through the saveAs method. You can consume the package from TypeScript and JavaScript projects alike.
I managed to get it work using this approach (Angular-CLI):
npm install file-saver --save npm install @types/file-saver --save
After that import Filesaver in component:
import * as FileSaver from 'file-saver';
And you can use it like this:
let blob = new Blob([document.getElementById('exportDiv').innerHTML], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-16le" }); FileSaver.saveAs(blob, "export.xls");
As you can see, you don't have to add anything in angular-cli.json. Just install library and it's types, import it and you are ready to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With