如何从Angular2中的其他组件调用组件中的函数?

如何从Angular2中的其他组件调用组件中的函数?

问题描述:

我正在开发一个Angular的web应用程序。如何从Angular2中的其他组件调用组件中的函数?

我有一个问题,有一个名为editor-component的组件,它包含一些操作编辑器的功能(例如,getValue())。而在其他组件中,我也需要调用editor-component中的函数,组件之间的关系不是父/子,而我正在使用ngx-bootstrap中的模态。

所以我的问题是有什么办法可以让所有其他组件使用editor-component中的功能?

+0

因为它不是父母/子女关系,所以您需要使用共享服务在组件之间进行通信。 – Ploppy

尝试使用服务来存储编辑器组件的功能。 模态有点困难。自举演示代码:

<button type="button" class="btn btn-primary" (click)="showModal()">Open a modal</button> 
<pre *ngFor="let message of messages">{{message}}</pre> 

<div class="modal fade" bsModal #modal="bs-modal" tabindex="-1" role="dialog" 
    aria-labelledby="mySmallModalLabel" aria-hidden="true" 
    (onShow)="handler('onShow', $event)" 
    (onShown)="handler('onShown', $event)" 
    (onHide)="handler('onHide', $event)" 
    (onHidden)="handler('onHidden', $event)"> 
    <div class="modal-dialog modal-sm"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <h4 class="modal-title pull-left">Modal</h4> 
     <button type="button" class="close pull-right" aria-label="Close" (click)="modal.hide()"> 
      <span aria-hidden="true">&times;</span> 
     </button> 
     </div> 
     <div class="modal-body"> 
     Just another modal <br> 
     Click <b>&times;</b>, press <code>Esc</code> or click on backdrop to close modal. 
     </div> 
    </div> 
    </div> 
</div> 

此模态位于组件范围内。并用这个#modal =“bs-modal”我们可以通过使用变量“modal”来使用上下文模式 更多信息http://valor-software.com/ngx-bootstrap/#/modals

+0

感谢您的回答。它有点不同,我使用的是'ngx-bootstrap',因此模式是一个入口组件,由服务切换。 – Zanecat

好吧,最后我得到了一个解决方案。

它在某种程度上与现有的类似,使用两个字段的共享服务。

editorService,设置getContentEvent和注册事件在二者并editorComponentotherComponent,设置字段content : string。当事件发出时,在editorComponent订阅事件并设置content在服务中提交,因此其他组件可以获得content