Home > Net >  How to access function from parent component when in modal component?
How to access function from parent component when in modal component?

Time:06-07

The refreshTable() function is in the parent component. I need to trigger it whenever I updated information in my modal and closes it.

I am using @ng-bootstrap for my modal

For may parent.component.ts

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

 constructor(
private ngbModal: NgbModal,
)

viewModal() {
    const openModal = this.ngbModal.open(ModalComponent);
    openModal .componentInstance.id = row.id;
}

refreshTable() {
    //refresh code block here
}

For my modal.component.ts

import { NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';

constructor(
private activeModal: NgbActiveModal,
)

updateParent() {
    //update data to database code here
    this.activeModal.close();
}

How to trigger refreshTable() from ModalComponent after closing the modal? Since there are changes in the data from database, data from parent is not updated accordingly when modal is closed.

CodePudding user response:

Try to change to this


const openModal = this.ngbModal.open(ModalComponent);
openModal.componentInstance.id = row.id;
openModal.dismissed.subscribe(
  _ => {
    this.refreshTable();
  }
)

in parent.component.ts

CodePudding user response:

Pass it from the parent component to the child component as a prop.

Use bind or an arrow function to preserve the this value.

CodePudding user response:

Add an output event to your modal component

@Output() onCLose: EventEmitter<any> = new EventEmitter();

When the user clicks close just call the emit() method

this.onCLose.emit(value); //value can be whatever you want to pass to the parent

Update your viewModal method in the parent to include a subscription to the close event

viewModal() {
   const openModal = this.ngbModal.open(ModalComponent);
   openModal.componentInstance.id = row.id;
   openModal.componentInstance.onClose.subscribe(value => 
      // handle the close event
      this.refreshTable();
   })
}

You could also do it any other way communication between components can be achieved:

  • service
  • state management (ngrx, etc)

CodePudding user response:

ngBootstrap modals have a beforeDismiss event, to which you can add logic before you close the modal. You have to return a truthy value for the modal to actually close.

You could do it like this:

const openModal = this.ngbModal.open(ModalComponent, { beforeDismiss: () => this.updateParent() }); // if modal is not closing, your function is returning false.

Check here for info on that function (do use ctrl F to find the option if needeD)

Edit: @tom-fong's answer is also a good solution, but you'd have to check if you're using version > 8.0.0

  • Related