Download A File In Angular


I’ll describe how to download a file in Angular by clicking a button in this article and provide an example.

Create an Angular Project

Let’s use the following command to start a new Angular project.

ng new demo

Use the following instructions to launch a project in Visual Studio Code.

cd demo
Code .
<div class="m-4">
  <button class="btn btn-dark">
    <a [href]="fileUrl" download="file.txt">Download File</a>
  <div id="container" class="d-none">Prinkesha Lathidadiya</div>
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
export class AppComponent {
  fileUrl: any;
  constructor(private sanitizer: DomSanitizer) {}
  ngOnInit() {
    const Value: any = document.getElementById('container')?.innerHTML;
    const blob = new Blob([Value], {
      type: 'application/octet-stream',
    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(

Now Run the project by issuing the command below.

npm start

then click the link, afterwards the downloaded file will be visible.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories