Reputation: 3
I am new to Angular, and I am having issues integrating szimek/signature_pad into my application. I have read articles on how to use JavaScript libraries in Angular 2+ apps, and they have worked with other libraries I have tried. However, I cannot get signature_pad to work. I am aware of angular versions of signature pad, however, I am required to use the JavaScript version.
Steps I have taken:
npm install --save signature_pad
npm install --save @types/signature_pad
import * as _signaturePad from 'signature_pad'; in app.component.ts
"scripts": ["src/app/js/signature_pad.js"]
in angular.json
<script src="./app/js/signature_pad.js"></script>
Every thing I have tried leads to an error. Can someone please help?
Upvotes: 0
Views: 1692
Reputation: 39408
It wasn't too hard for me to get this working in a new Angular project.
You had the first steps right. Create a new Angular app with the CLI and install signature_pad library:
npm install --save signature_pad
Note, I did not install the types library, but there is no reason you can't. I did not have to add this library to the Angular.json because the Angular CLI will include it in the main app automagically from the node_modules once we import it.
Before we jump into the typescript, make sure you have a canvas set up in app.component.html
. I just deleted all the defaults and added this:
<canvas #canvas></canvas>
Note that I use the #canvas
syntax as part of the canvas. This is so I can access this in code.
Now move to your app.component.ts
file. I'll go over my changes from top to bottom.
First, import the library, like this:
import SignaturePad from 'signature_pad';
Then, be sure the class implements the OnInit
interface. You'll need an import for this:
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
And you'll have to add the implements text after the AppComponent class definition:
export class AppComponent implements OnInit {
Now, inside the component class, create an instance variable for the signature pad:
public signaturePad: SignaturePad;
Create a ViewChild for the canvas:
@ViewChild('canvas', {static: true }) public canvas: ElementRef;
And finally, add an ngOnInit()
method:
ngOnInit() {
this.signaturePad = new SignaturePad(this.canvas.nativeElement);
}
The ngOnInit()
method initializes the SignaturePad class, per the instructions in the read me by passing into it the HTML element that will be used for the base. We get that by introspecting the nativeElement
on our ViewChild
.
Once I did this, everything worked fine.
You should be able to easily wrap this library up in an Angular component if you wished, and there are a bunch of APIs in the library I did not use for the purposes of this sample. You'll need to delve into the sample from the lib repo to see how they do things like change the color, clear, or save the signature.
Upvotes: 1