2017-09-16 73 views
1

我在我的應用程序中使用ngx-bootstrap並需要使用他們的模態。我想要做的是從我的父組件調用模態,在模態中執行某些操作,單擊保存按鈕,然後將該數據返回給父項,以便可以根據結果運行方法。從孩子的父母的Angular2模態調用方法

我的父組件調用modalService並將組件加載到其中。

this._bsModalRef = this._modalService.show(ConfirmActiveModalComponent);

被加載中有一個單一的方法,save()的組件。

父組件:

import { ConfirmActiveModalComponent } .... 

openModal(){ 
    this._bsModalRef = this._modalService.show(ConfirmActiveModalComponent); 
} 

addNewRecord(){ 
    // I need this to run when the modal "Save" button is clicked 
} 

模態分量:

@Component({ 
    selector: 'app-confirm-existing-version-modal', 
    templateUrl: './confirmExistingVersionModal.component.html', 
    styleUrls: ['./confirmExistingVersionModal.component.css'] 
}) 

export class ConfirmExistingVersionModalComponent { 

    constructor(
     public _bsModalRef: BsModalRef, 
    ) { } 

    save() { 
     // Some data here from the modal 
    } 

} 

模態分量HTML:

<div> 
    <div class="modal-header text-center"> 
     <h4 class="modal-title">Confirmation</h4> 
    </div> 
    <div class="modal-body"> 
     xx 
    </div> 
    <div class="modal-footer"> 
     <button type="button" class="btn btn-default" (click)="_bsModalRef.hide()">Close</button> 
     <button type="button" class="btn btn-default" (click)="save()">Save</button> 
    </div> 
</div> 

如何在我的父項中運行addNewRecord()方法時,單擊我的模式中的保存按鈕?

我沒有看到從bsModalRef返回的任何回調或承諾,所以不知道從哪裏開始。我是否真的需要在我的父母中爲每個我將調用的模態創建一個訂閱,以便監聽它自己發出的模式數據?

回答

1

您可以在模態分量創建EventEmitterSubject財產發出從子組件的一些數據:

模態分量:

export class ConfirmExistingVersionModalComponent { 
    saved: EventEmitter<any> = new EventEmitter(); 
    ... 
    save() { 
    this.saved.emit('someData'); 
    } 
} 

然後所有你需要做的是訂閱在您的父組件中發生此事件:

父組件:

import 'rxjs/add/operator/take'; 
... 

openModal(){ 
    this._bsModalRef = this._modalService.show(ConfirmExistingVersionModalComponent); 
    this._bsModalRef.content.saved.take(1).subscribe(this.addNewRecord.bind(this)) 
} 

addNewRecord(someData){ 
    alert(`Save button has been clicked. Data received: ${someData}`); 
} 

Plunker Example

+0

驚人的。我已經花了好幾個小時,試圖拿出一個解決方案。這是一種非常常見的方法,還是模式庫提供某種回調/承諾更爲理想? – SBB

+1

這是動態創建組件的常用方法 – yurzui