Search code examples
javascriptangulartypescriptngx-bootstrap

ngx-bootstrap BsModal closing from child component


I have a scenario after saving data to database I need to close the Bs-modal popup, and my saving is done in the child component so I passed the Bs-modal in the child component using ()Input and using there to hide the pop up but not able to read my modal in the child component

HTML Parent Component

<div bsModal #lgModal2="bs-modal" class="modal fade" tabindex="-1" 
     role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
          <h4 class="modal-title pull-left">Edit Product</h4>
          <button type="button" class="close pull-right" (click)="lgModal2.hide()" aria-label="Close">
          <span aria-hidden="true">&times;</span>
          </button>
          </div>
           <div class="modal-body">
           <app-edit-product [productId]="prodId" [modalId]="lgmodal2" #child ></app-edit-product>

           </div>
       </div>
     </div>
   </div>

Child Component TS

import { BsModalRef } from 'ngx-bootstrap';
export class EditProductComponent implements OnInit {
  @Input() modalId:BsModalRef;
  somefunction(){
    this.modalId.hide();
  }
}

Error:An Unexpected error occured!TypeError: Cannot read property 'hide' of undefined

Also tried

@Output() closeModal:EventEmitter<Event> = new EventEmitter();
@Input() onHide:any;

then

 somefunction(){
   this.closeModal.emit(this.onHide);
  }

any help will be great thanks!


Solution

  • HTML Parent:

    <div bsModal #lgModal2="bs-modal" class="modal fade" tabindex="-1" 
         role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">
              <div class="modal-header">
              <h4 class="modal-title pull-left">Edit Product</h4>
              <button type="button" class="close pull-right" (click)="hideModal()" aria-label="Close">
              <span aria-hidden="true">&times;</span>
              </button>
              </div>
               <div class="modal-body">
               <app-edit-product [productId]="prodId" [modalId]="lgmodal2" (saveDone)="hideModal()" #child ></app-edit-product>
    
               </div>
           </div>
         </div>
       </div>
    

    CHILD COMPONENT TS:

    export class EditProductComponent implements OnInit {
      @Output() saveDone: EventEmitter<any> = new EventEmitter<any>();
      somefunction(){
        this.saveDone.emit();
      }
    }
    

    PARENT COMPONENT TS:

    import { Component, ViewChild } from '@angular/core';
    import { ModalDirective } from 'ngx-bootstrap/modal';
    export class ParentComponent implements OnInit {
        @ViewChild('lgModal2') lgModal2: ModalDirective;
        hideModal(){
           this.lgModal2.hide();
        }
    }
    

    Hope this helps.