Angular 2 NgbModal NgbActiveModal close event modal

Dany G picture Dany G · Jun 16, 2017 · Viewed 28.9k times · Source

I'm using Angular 2, I'm working with a form modal, I have two components, from one component I open the form modal this way:

import { Component, OnInit, Output} from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { MyFormComponent } from '......./....';


@Component({
    moduleId: module.id,
    selector: 'my-component',
    templateUrl: 'my-component.html'
})
export class MyComponent implements OnInit {

    private anyData: any;
    private anyDataForm: any;


    constructor(
        private modalService: NgbModal
    ) { }

    ngOnInit(): void {
    }

    open() {
        const modalRef = this.modalService.open(MyFormComponent, { size: 'lg' });
        modalRef.componentInstance.anyDataForm = this.anyData;
    }

    possibleOnCloseEvet() { 
        //Do some actions....
    }

}

The open() method fires from a button on my-component.html

And on the Form component (the modal one) I use this for close the actual modal (from itself)

import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    moduleId: module.id,
    selector: 'my-form-component',
    templateUrl: 'my-form-component.html'
})
export class MyFormComponent implements OnInit, OnDestroy {

    @Input() anyDataForm: any;

    constructor(
        public activeModal: NgbActiveModal
    ) {
    }

    ngOnInit(): void {
    }

    //Some form code...

    OnSubmit() {
        this.activeModal.close(); //It closes successfully
    }

    ngOnDestroy(): void {
    }

}

What I need to do is fire some kind of "on close" event on the caller component to perform some actions in the caller only when the modal is closed. (can't use event emmiter)

Is there any way for the component opener to know when the modal close? I have not found any clear example of this.

Answer

Adnan A. picture Adnan A. · Jun 17, 2017

Try this:

const modalRef = this.modalService.open(MyFormComponent, { size: 'lg' });
modalRef.componentInstance.anyDataForm = this.anyData;

modalRef.result.then((data) => {
  // on close
}, (reason) => {
  // on dismiss
});