ViewChild返回“未定义"

编程入门 行业动态 更新时间:2024-10-27 06:23:36
本文介绍了ViewChild返回“未定义"-Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图通过按下父级上的按钮来执行子级组件的功能,但由于某种原因,它的功能未定义.

I'm trying to execute a function of a child component with a push of a button on the parent but for some reason its undefined.

父母:

.. com1.html <ng-template #content let-c="close" let-d="dismiss"> <div class="modal-header"> <h4 class="modal-title">Title</h4> </div> <div class="modal-body" style="display: flex; justify-content: center;"> <app-com2 [var1]="value" #traceRef></app-com2> </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-dark" (click)="savePNG()"><i class="fa fa-download"></i>PNG</button> <button type="button" class="btn btn-outline-dark" (click)="c()">Close</button> </div> </ng-template> <button class="btn btn-sm btn-secondary" (click)="open(content)">Button</button> ..1.ts export class com1 implements OnInit { @ViewChild('traceRef') traceRef; value = "something"; constructor(private modalService: NgbModal) {} savePNG() { this.traceRef.savePNG(); } open(content: any) { this.modalService.open(content, { windowClass: 'temp-modal' }); } }

有人能指出我正确的方向吗,因为其他线程没有帮助:( 即使使用ngAfterViewInit,它仍未定义.

Could anyone point me in the right directions cuz the other threads were of no help :( Even with ngAfterViewInit its still undefined.

推荐答案

与ng-template常见情况一样,它不起作用的原因是NgbModal服务创建模板并且未将其附加到父视图,而是以根ApplicationRef

The reason why it is not working as it would be in common scenario with ng-template is that NgbModal service creates template and doesn't attach it to parent view but rather to root ApplicationRef

const viewRef = content.createEmbeddedView(context); this._applicationRef.attachView(viewRef);

https ://github/ng-bootstrap/ng-bootstrap/blob/0f8055f54dad84e235810ff7bfc846911c168b7a/src/modal/modal-stack.ts#L107-L109

这意味着您的查询对于您的组件将永远是干净的.

This means your query will be always undirty for your component.

在常见情况下(请参阅由@ConnorsFan提供的示例),我们使用vcRef.createEmbeddedView负责检查父视图中的查询:

In common cases(see example provided by @ConnorsFan) we use vcRef.createEmbeddedView which is responsible for checking queries in parent view:

vcRef.createEmbeddedView || \/ function attachEmbeddedView( ... Services.dirtyParentQueries(view); <========== set dirty for queries

github/angular/angular/blob/0ebdb3d12f8cab7f9a24a414885ae3c646201e90/packages/core/src/view/view_attach.ts#L12-L23

我在这里可以看到的简单解决方案是直接在模板中通过或调用引用:

The simple solution i can see here is just pass or call reference directly in template:

(click)="traceRef.savePNG()"

更多推荐

ViewChild返回“未定义"

本文发布于:2023-11-22 23:15:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619297.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未定义   ViewChild   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!