0
votes

I am developing an angular project with angular2-signaturepad. I'm trying to access a component in the template, so I created a @ViewChild. But when I try to use it, it's undefined.

Here's the relevant html snippet:

<signature-pad [options]="options" (onBeginEvent)="drawBegin()" (onEndEvent)="drawComplete()"></signature-pad>

Here's the snippet from the typescript file:

@ViewChild(SignaturePad, {static: true}) public signaturePad: SignaturePad;

Since this.signaturepad is undefined, I can't call any of its functions that I need. Can any one help me with this?

1
in the future, it could be helpful to indicate the place where you've accessed this.signaturePad and found it to be undefined (for example, in the constructor of the component, or ngOnInit) - SnailCoil

1 Answers

0
votes

There are a few things that could be happening here.

You could be trying to access the ViewChild before it exists. ViewChildren will be resolved before ngAfterViewInit is called (more information on lifecycle events here), so you would only be able to guarantee that it's defined in that function. for example:

export class MyComponent implements AfterViewInit, OnChanges {
    @ViewChild(SignaturePad, {static: true}) public signaturePad: SignaturePad;

    constructor() {
        console.log(this.signaturePad); // always undefined
    }

    ngOnChanges(changes) {
        console.log(this.signaturePad); // sometimes undefined, sometimes defined
    }

    ngAfterViewInit() {
        console.log(this.signaturePad); // defined!
    }

The other thing that could be happening is the use of static: true, which means the ViewChild will be resolved before change detection (more information on ViewChild here). The implication of that would be, if <signature-pad> is nested inside of another element which happens to be conditional, then the ViewChild won't be resolved. for example:

<div *ngIf="allowEdit" class="my-container">
    <signature-pad ...></signature-pad>
</div>

Then in the class, the ViewChild would not be defined

ngAfterViewInit() {
    console.log(this.signaturePad); // undefined
}

If this is your situation, then changing {static: true} to {static: false} should fix it