How to download a file from a url when a button is clicked in angular5 / 6
You can make the button look like an anchor element through html, for instance:
<a href="abc.net/files/test.ino">download</a>
You can also try and create a dynamic anchor element:
let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = 'abc.net/files/test.ino';
link.download = path;
document.body.appendChild(link);
link.click();
link.remove();
Adding on to Hussains answer but just doing it with Renderer2 since its not advised to use document directly.
import { Renderer2 } from '@angular/core'
export class SomeComponent {
constructor(private renderer: Renderer2) {}
downloadFile() {
const link = this.renderer.createElement('a');
link.setAttribute('target', '_blank');
link.setAttribute('href', 'abc.net/files/test.ino');
link.setAttribute('download', `products.csv`);
link.click();
link.remove();
}
}
you can create an anchor tag to download the file on button click event
downloadMyFile(){
const link = document.createElement('a');
link.setAttribute('target', '_blank');
link.setAttribute('href', 'abc.net/files/test.ino');
link.setAttribute('download', `products.csv`);
document.body.appendChild(link);
link.click();
link.remove();
}
now call this function from your button
<button (click)="downloadMyFile()">download File<button>