Angular 2 Best approach to use FileSaver.js

Naveed Ahmed picture Naveed Ahmed · Oct 25, 2016 · Viewed 39k times · Source

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.

Answer

Tomislav picture Tomislav · Jan 25, 2017

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.