我们在应用程序中使用模式(ng-bootstrap's one)。该模态如下:
<ng-template #modal let-modal>
<app-audio #audio></app-audio>
</ng-template>
这是逻辑:
@ViewChild('modal')
modal: ElementRef;
@ViewChild('audio')
audio: AudioComponent;
模态通过以下方式打开:
this.modalService.open(this.modal,{size:'lg'});
到这里一切都很好。模态打开,并显示音频组件。但是现在,我们想要访问组件内部的逻辑,以及执行类似的操作时
this.audio.somePublicComponentFunction()
碰巧this.audio为null。我已经尝试过让孩子使用角度的变化检测器,但是无法找到一种将this.audio与实际组件正确链接的方法。有任何想法吗?非常感谢。
You can see the issue here: stackblitz.com/edit/angular-ofmpju
答案 0 :(得分:3)
您可以从模板本身调用方法audio.someFunction()
。
<ng-template #modal let-modal>
<div style="background-color: red;">
<h1>Modal header</h1>
<app-audio #audio></app-audio>
<!-- on click, call audio comp method someFunction() using its reference -->
<button (click)="audio.someFunction()">Operate with audio from inside modal</button>
</div>
</ng-template>
此处不需要@ViewChild
属性。这应该为您解决问题。
分叉的demo
答案 1 :(得分:2)
您可以读取不带refrence变量的子组件
@ViewChild(AudioComponent)
audio: AudioComponent;
这将为您提供子组件的实例-您可以在其中访问方法
this.audio.someComponentFunction()
您的html
<ng-template #modal let-modal>
<app-audio></app-audio>
</ng-template>
我认为这将解决您的问题-编码愉快
更新:
希望我找到了解决此问题的方法-如果仅触发一个函数,则可以使用此方法
我刚刚使用getter
和setter
添加了一个属性,并在我们set
值时触发了该函数
@Input()
get triggerFunction(): boolean {
return this.runFuntion;
}
set triggerFunction(value: boolean) {
this.runFuntion = value;
this.someFunction();
}
因此,这会导致每次显示模型时都触发函数-上述属性属于嵌套在<ng-template>
中的子组件,因此最终,模型模板将如下所述:
<ng-template #modal let-modal>
<app-audio [triggerFunction]="true"></app-audio>
</ng-template>
希望这会暂时解决-谢谢
答案 2 :(得分:0)
对我来说,所有这些解决方案都行不通,我仍然想在第三方ng-template中访问自己的组件。这是我的“解决方案”。我不认为这是最佳实践,而是一个拼命的解决方案,可以得到我想要的;-)当然,它仅适用于您自己的组件。
=SUM(A1+A2)