我正在与angular2-signaturepad开发一个angular项目。我试图访问模板中的一个组件,所以我创建了一个@ViewChild。但当我尝试使用它时,它是未定义的。
下面是相关的html代码片段:
<signature-pad [options]="options" (onBeginEvent)="drawBegin()" (onEndEvent)="drawComplete()"></signature-pad>下面是typescript文件中的代码片段:
@ViewChild(SignaturePad, {static: true}) public signaturePad: SignaturePad;因为this.signaturepad是未定义的,所以我不能调用任何我需要的函数。有人能帮我这个忙吗?
发布于 2020-08-13 01:11:49
这里可能会发生一些事情。
您可能试图在ViewChild存在之前访问它。ViewChildren将在ngAfterViewInit被调用(more information on lifecycle events here)之前被解析,所以您只能保证它是在该函数中定义的。例如:
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!
}另一个可能发生的事情是static: true的使用,这意味着ViewChild将在更改检测(more information on ViewChild here)之前得到解决。这意味着,如果<signature-pad>嵌套在另一个恰好是有条件的元素中,那么ViewChild将不会被解析。例如:
<div *ngIf="allowEdit" class="my-container">
<signature-pad ...></signature-pad>
</div>则在类中将不会定义ViewChild
ngAfterViewInit() {
console.log(this.signaturePad); // undefined
}如果这是您的情况,那么将{static: true}更改为{static: false}应该可以解决这个问题
https://stackoverflow.com/questions/63380773
复制相似问题