Need to utilize modals using ngx-bootstrap. Tried by calling modal from parent component, do task within the modal, click save, then give that data back to parent to run a method based on result.
Parent component calls the modalService
and loads a component into it.
this._bsModalRef = this._modalService.show(ConfirmActiveModalComponent);
Component loaded has a single method in it: save()
.
Parent Component:
import { ConfirmActiveModalComponent } ....
openModal(){
this._bsModalRef = this._modalService.show(ConfirmActiveModalComponent);
}
addNewRecord(){
// I need this to run when the modal "Save" button is clicked
}
Modal Component:
@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
}
}
Modal Component 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>
How to run the addNewRecord()
method in parent when clicking on save button in modal?
I didn't see any callbacks or promises returned from bsModalRef
, so don't know where to start. Do I create a subscription in parent for each modal called, to be able to listen for data emitted by modal?
You can create EventEmitter
or Subject
property in your modal component to emit some data from child component:
Modal Component:
export class ConfirmExistingVersionModalComponent {
saved: EventEmitter<any> = new EventEmitter();
...
save() {
this.saved.emit('someData');
}
}
And then all you need to do is subscribe to this event in your parent component:
Parent Component:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With