我试图通过按父组件上的按钮来执行子组件的功能,但由于某种原因它未定义。
Parent:
.. 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 它仍然是未定义的。
它不能像常见情况下那样工作的原因ng-template
就是它NgbModal
服务创建模板,但不会将其附加到父视图,而是附加到根视图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 https://github.com/ng-bootstrap/ng-bootstrap/blob/0f8055f54dad84e235810ff7bfc846911c168b7a/src/modal/modal-stack.ts#L107-L109
这意味着您的查询对于您的组件来说始终是不脏的。
常见情况下(参见example https://stackblitz.com/edit/angular-22u1jl由@ConnorsFan 提供)我们使用vcRef.createEmbeddedView
它负责检查父视图中的查询:
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 https://github.com/angular/angular/blob/0ebdb3d12f8cab7f9a24a414885ae3c646201e90/packages/core/src/view/view_attach.ts#L12-L23
我在这里看到的简单解决方案就是直接在模板中传递或调用引用:
(click)="traceRef.savePNG()"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)