来自子的父级的Angular2模态调用方法

时间:2017-09-16 22:33:03

标签: angular bootstrap-modal

需要使用ngx-bootstrap来使用模态。通过从父组件调用模态来尝试,在模态中执行任务,单击保存,然后将该数据返回给父级以基于结果运行方法。

父组件调用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 个答案:

答案 0 :(得分:5)

您可以在模态组件中创建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

相关问题