Download blob as a file in Angular

Recently I got a requirement to download base64 string as .pfx file in Angular application.

So I did that using Blob API in javascript.

More about Blob

So I did a sample application on stackblitz using Angular.

const data = 'some text';
const blob =new Blob([data],{type:'application/octet-stream'});
this.fileUrl =this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));

As above we need to create Blob object. As second parameter we need to specify Mime type. And in Angular to make the Blob url safe in DOM we can use DomSanitizer.

We have to import DomSanitizer

import { DomSanitizer } from '@angular/platform-browser';</div>
// constructor
constructor(private sanitizer: DomSanitizer) { }

In html template

<a>DownloadFile</a>

Working sample on stackblitz

🙂

 

 

 

Advertisements

Disabled directive in angular

Problem:

When using reactive form in angular disabled property binding does not work in template.

Solutions:

  1. Using disable method programmatically in form control.
  2. Create directive

In my case I couldn’t use disabled since my input is not a control in form. It’s just a input in template.

So I created directive.

You can find it here. It might help some one having my requirement.

Live demo

import { Directive, ElementRef, Input } from ‘@angular/core’;
import { OnChanges } from ‘@angular/core/src/metadata/lifecycle_hooks’;

/**
* Directive for add disable attribute to input element
* Eg: [appInputDisabled]=”isDisabled”
* @export
* @class InputDisabledDirective
* @implements {OnChanges}
*/
@Directive({
selector: ‘[appInputDisabled]’
})

export class InputDisabledDirective implements OnChanges {
@Input() appInputDisabled: boolean;

constructor(private el: ElementRef) { }

ngOnChanges(): void {
this.el.nativeElement.disabled = (this.appInputDisabled) ? true : false;
}

}

Source code here ….

Code on stackblitz