Skip to content

Instantly share code, notes, and snippets.

@Phury
Created February 24, 2023 16:13
Show Gist options
  • Save Phury/5f0c660addf47bdc42f1cb16eb764941 to your computer and use it in GitHub Desktop.
Save Phury/5f0c660addf47bdc42f1cb16eb764941 to your computer and use it in GitHub Desktop.
AngularX download file directive
<button mat-flat-button class="download-btn" onDownloadFile
[downloadFunc]="downloadCsr.bind(this)"
[contentType]="'application/pkcs10'"
[fileName]="cert.commonName + '.pem'">
{{'certificate.detail.downloadCSR' | translate}}
</button>
@Directive({
selector: '[onDownloadFile]'
})
export class DownloadFileDirective {
@Input() downloadFunc: () => Observable<string[]> = () => of();
@Input() contentType: string = '';
@Input() fileName: string = '';
@HostListener('click', ['$event'])
onClick() {
this.downloadFunc().subscribe((value: string[]) => this.downloadFile(
new Blob(value, {type: this.contentType}),
this.fileName
));
}
downloadFile(data: Blob, fileName: string) {
const a = document.createElement('a');
const objectUrl = URL.createObjectURL(data);
a.href = objectUrl;
a.download = fileName;
a.click();
URL.revokeObjectURL(objectUrl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment