Download A File In Angular

Introduction

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 .
App.Component.html
<div class="m-4">
  <button class="btn btn-dark">
    <a [href]="fileUrl" download="file.txt">Download File</a>
  </button>
  <div id="container" class="d-none">Prinkesha Lathidadiya</div>
</div>
App.Component.ts
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  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(
      window.URL.createObjectURL(blob)
    );
  }
}

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 *

Subscribe

Select Categories