How To Add Signature Pad In Angular

Introduction:

Signature pad is One of the most crucial components of a daily online or mobile application. Using third-party libraries, we can quickly integrate this feature into our application using angular. We can also add signatures without using any third party also.

Popular eCommerce businesses like Amazon have been known to provide the option of putting signatures on a device when we receive our orders.

This project offers digital signature tools and components. Utilize it to create digital signatures using the HTML5 canvas.

let’s start code…

First of all create a new project by applying following command in terminal.

ng new signatureDemo

After creating project install signature pad npm to use it in our project. This is done by using following command.

npm i signature_pad --save

We must include a canvas in our app.component.html template so that we can draw our signature.

app.component.html

<canvas #canvas (touchstart)="startDrawing($event)"></canvas>

<button (click)="clearPad()">Clear</button>
<button color="secondary" (click)="savePad()">Save</button>
<img src='{{ signatureImg }}' />

Here we have two button that is clear and save. One to clear the signature canvas and the other to get signature data in base64 string format.

app.component.ts

import { Component, ElementRef, ViewChild } from '@angular/core';
import SignaturePad from 'signature_pad';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'signatureJS';
  signaturePad: SignaturePad;
  @ViewChild('canvas') canvasEl: ElementRef;
  signatureImg: string;

  constructor() { }

  ngAfterViewInit() {
    this.signaturePad = new SignaturePad(this.canvasEl.nativeElement);
  }

  startDrawing(event: Event) {
    console.log(event);
    // works in device not in browser

  }

  clearPad() {
    this.signaturePad.clear();
  }

  savePad() {
    const base64Data = this.signaturePad.toDataURL();
    this.signatureImg = base64Data;
  }

}

In above we import signature pad to use it draw signature on canvas. In this code we are using the method todataURL for converting the file base64 image data. Clear method is used to clear data on canvas.

app.component.css

canvas {
    display: block;
    border: 1px solid rgb(187, 178, 178);
    background-color: var(--ion-color-success);
}
button {
    margin: 10px;
    margin-left: 10px;
}

OUTPUT:

Conclusion:

In this tutorial we have completed drawing and capturing signatures in our Angular application using third-party library that is Javascript signature_pad library. We can easily display all of the signature data in our template, and base64 can also be converted to an image file. All signature data is recorded in base64 format.

Submit a Comment

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

Subscribe

Select Categories