Angular 2 NgbModal NgbActiveModal модальное событие закрытия

Я использую Angular 2, я работаю с модальной формой, у меня есть два компонента, из одного компонента я открываю модальную форму следующим образом:

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....
    }

}

Метод open () запускается с помощью кнопки на my-component.html.

И в компоненте формы (модальном) я использую это для закрытия фактического модального (от самого себя)

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 {
    }

}

Что мне нужно сделать, так это запустить какое-то событие «при закрытии» в компоненте вызывающей стороны, чтобы выполнить некоторые действия в вызывающей стороне только тогда, когда модальное окно закрыто. (не может использовать эмитент событий)

Есть ли способ для средства открытия компонентов узнать, когда модальное закрытие? Я не нашел наглядного примера этого.


person Dany G    schedule 16.06.2017    source источник


Ответы (4)


Попробуй это:

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

modalRef.result.then((data) => {
  // on close
}, (reason) => {
  // on dismiss
});
person Adnan A.    schedule 17.06.2017
comment
Я просто хотел запустить некоторые службы при закрытом модальном режиме, поэтому я использовал finally () вместо того, чтобы Приветствовать @Adnan - person Deviprasad Sharma; 02.07.2021

На моем ModalformComponent

 this.activeModal.close('success');

Затем в моем родительском компоненте ListComponent

 this.modalRef = this.modalService.open(ModalformComponent);
 this.modalRef.componentInstance.title = 'Add Record';
 this.modalRef.result.then((result) => {
  if ( result === 'success' ) {
     this.refreshData(); // Refresh Data in table grid
  }
}, (reason) => {
});
person David Njuguna    schedule 18.02.2019

в MyFormComponent можно добавить

closeModal() { this.activeModal.close( anything ); }
person octavian09    schedule 06.03.2018

Вместо this.activeModal.close(); используйте this.activeModal.dismissAll(). Это успешно закроет всплывающее окно.

person Hari    schedule 30.10.2019
comment
OP может успешно закрыть модальное окно. Что нужно было, так это как-то прислушаться к его закрытию в коде, который его открыл, чтобы они могли запустить какой-то код, например, обновить данные в нем. - person Guilherme Taffarel Bergamin; 27.01.2021