2017-09-16 72 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