Introduction

Here, we will learn how to generate a QR code dynamically using Angular 7 and download it. It's now a basic requirement of many applications to generate and download the QR code.
Prerequisites
Let’s get started.
Open Visual Studio Code and open a new terminal.
Generate And Download QR Code Using Angular 7
Type the following command to generate the new Angular 7 application.
  1. ng new generate-qrcode --routing
Generate And Download QR Code Using Angular 7
Now, open the project by opening the folder from Visual Studio Code.
We have to install the QR Code package - the functionality for generating the QR code from the text.
Type the following command in the terminal.
  1. npm install ngx-qrcode2 --save

Now, the package will be installed in our application.

Go to the app.module.ts file add a reference there for the QR code package.

  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { NgModule } from '@angular/core';
  3. import { AppRoutingModule } from './app-routing.module';
  4. import { AppComponent } from './app.component';
  5. import { NgxQRCodeModule } from 'ngx-qrcode2';
  6. import { FormsModule } from '@angular/forms';
  7. @NgModule({
  8. declarations: [
  9. AppComponent
  10. ],
  11. imports: [
  12. BrowserModule,
  13. AppRoutingModule,
  14. NgxQRCodeModule,
  15. FormsModule
  16. ],
  17. providers: [],
  18. bootstrap: [AppComponent]
  19. })
  20. export class AppModule { }
Open the app.component.html file and add the code in it.
  1. <!--The content below is only a placeholder and can be replaced.-->
  2. <div style="text-align:center">
  3. <input type="text" placeholder="Enter name to generate QR Code" [(ngModel)]="qrcodename"><br>
  4. <button (click)="generateQRCode()">Generate QR Code</button>
  5. <ngx-qrcode *ngIf="display" id="qrCodeImage" [qrc-element-type]="elementType" [qrc-value] = "value">
  6. </ngx-qrcode><br>
  7. <a [href]="href" *ngIf="display" (click)="downloadImage()" download>Download Image</a>
  8. </div>
  9. <router-outlet></router-outlet>
Finally, open the app.component.css file and add some CSS in it.
  1. button {
  2. padding: 10px;
  3. background-color: skyblue;
  4. margin-top: 10px;
  5. }
  6. input {
  7. padding: 10px;
  8. width: 15%;
  9. }
  10. a {
  11. padding: 10px;
  12. background-color: skyblue;
  13. margin-top: 10px;
  14. text-decoration: none;
  15. }
That's it. We are done with it.
Run the application by typing the ng serve command.

Output

Generate And Download QR Code Using Angular 7
You can download the source code from here.
You can also refer to the next article that tells about reading the data of QR code from here.
Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.