You can do this using bypassSecurityTrustUrl() method from DomSanitizer.
app.component.ts
export class AppComponent {
downloadUrl;
filename = "";
constructor(private sanitizer: DomSanitizer) {
this.generateUrl();
}
generateUrl() {
var res = { appname: "ABCD", appid: 1234 };
this.filename = res.appname + res.appid;
var data = JSON.stringify(res);
var url = this.sanitizer.bypassSecurityTrustUrl(
"data:text/json;charset=UTF-8," + encodeURIComponent(data)
);
this.downloadUrl = url;
}
}
app.component.html
<a [href]="downloadUrl" download="{{filename}}.json">Download</a>
Note that it is only the code snippet that required for Json file creation and linking with a download link.
Also, you can keep the filename as your wish. Currently, the filename is created using the json data.
If you are interested to check the live demo then you can go with the following link.
https://codesandbox.io/s/download-json-angular-k9fvz?file=/src/app/app.component.ts
<a [href]="myDataUrl">developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/…. You can just look up any JavaScript answer that explains it, it's the same in Angular.