ViewChild返回“未定义"-Angular2 [英] ViewChild returns 'undefined' - Angular2

查看:104
本文介绍了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>

...com1.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.com/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

https://github.com/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返回“未定义"-Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆