2017-08-12 56 views
-2

我正在開發一個Angular的web應用程序。如何從Angular2中的其他組件調用組件中的函數?

我有一個問題,有一個名爲editor-component的組件,它包含一些操作編輯器的功能(例如,getValue())。而在其他組件中,我也需要調用editor-component中的函數,組件之間的關係不是父/子,而我正在使用ngx-bootstrap中的模態。

所以我的問題是有什麼辦法可以讓所有其他組件使用editor-component中的功能?

+0

因爲它不是父母/子女關係,所以您需要使用共享服務在組件之間進行通信。 – Ploppy

回答

1

嘗試使用服務來存儲編輯器組件的功能。 模態有點困難。自舉演示代碼:

<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

0

好吧,最後我得到了一個解決方案。

它在某種程度上與現有的類似,使用兩個字段的共享服務。

editorService,設置getContentEvent和註冊事件在二者並editorComponentotherComponent,設置字段content : string。當事件發出時,在editorComponent訂閱事件並設置content在服務中提交,因此其他組件可以獲得content

相關問題