ngx-bootstrap modal: How to get a return value from a modal?

前端 未结 9 1519
一向
一向 2020-12-13 02:23

In my Angular 4 app, let\'s assume that I\'m inside a service.

At some point, I want to ask the user for a confirmation, currently I\'m doing it with just a co

9条回答
  •  鱼传尺愫
    2020-12-13 03:00

    I understand that most of the answers above are completely valid, but that the main goal is be able to invoke the confirmation dialog in this way...

      async openModalConfirmation() {
        const result = await this.confirmationSvc.confirm('Confirm this...');
        if (result) {
          console.log('Yes!');
        } else {
          console.log('Oh no...');
        }
      }
    

    Note that this is mostly syntactic sugar to simplify the use of a promise and the asynchronous stuff.

    I think it's what the OP was looking for and probably can be reworked to support returning any other data type (apart from a boolean).

    The rest of the code below (not including the template to keep this short), pretty straightforward..

    ModalConfirmationService

    import { ModalConfirmationComponent } from './component';
    
    @Injectable()
    export class ModalConfirmationService {
    
      constructor(private bsModalService: BsModalService) {}
    
      confirm(message: string): Promise {
        const modal = this.bsModalService.show(ModalConfirmationComponent, { initialState: { message: message }});
    
        return new Promise((resolve, reject) => modal.content.result.subscribe((result) => resolve(result) ));
      }
    }
    

    ModalConfirmationComponent

    import { Component, Input, Output, EventEmitter} from '@angular/core';
    import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
    import { Subject } from 'rxjs/Subject';
    
    @Component({
      templateUrl: './component.html'
    })
    export class ModalConfirmationComponent {
      @Input() message: string;
      result: Subject = new Subject();
    
      constructor(public modalRef: BsModalRef) { }
    
      confirm(): void {
        this.result.next(true);
        this.modalRef.hide();
      }
    
      decline(): void {
        this.result.next(false);
        this.modalRef.hide();
      }
    }
    

提交回复
热议问题