我试图通过按下父级上的按钮来执行子级组件的功能,但由于某种原因,它的功能未定义.
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 queriesgithub/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返回“未定义"
发布评论