Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from the child modal to the parent

When I created a SeleccionServicioComponentMD modal window (child), I used this way:https://valor-software.com/ngx-bootstrap/#/modals#service-component

Inside the child there is button. When it is clicked:
1) the parent should close this child.
2) the parent should display another modal.

My attempt: The child (modal) emits an event to its parent but:
3) the parent didn't include an <app-seleccion-servicio-component> tag inside its HTML because its child was dynamically created. So, where does the parent listen for this emitted event from its children?

The expected result is:
4) click on the button inside the child component.
5) the parent closes this child (modal window).
6) the parent shows another modal window.

7) I am stuck on this point. I don't know how to do so that the parent listens the event emitted by its parent with no <app-seleccion-servicio-component> tag.

like image 239
Abelardo León González Avatar asked Dec 07 '17 19:12

Abelardo León González


2 Answers

Can't say much without looking at your code but you can create an EventEmitter in your child component and subscribe to it from parent.

Example: https://plnkr.co/edit/b6qHpolJmUFy7dYvYpkJ?p=preview

  /* CHILD COMPONENT */
  public event: EventEmitter<any> = new EventEmitter();

  triggerEvent() {
    this.event.emit({data: 12345});
  }

  /* PARENT COMPONENT */
 this.bsModalRef.content.event.subscribe(data => {
    console.log('Child component\'s event was triggered', data);
 });
like image 98
IlyaSurmay Avatar answered Sep 18 '22 16:09

IlyaSurmay


Related to Angular 7, I could managed the scenario as follows.

parent-component.ts

bsModalRef: BsModalRef;

 loadModal() {
    const initialState = {
      title: 'Appointments'
    };

    this.bsModalRef = this.modalService.show(ModalComponent, {
      initialState,
      class: 'modal-lg'
    });

    this.bsModalRef.content.messageEvent.subscribe(data => {
      console.log('Child component\'s event was triggered', data);
    });
  }

parent-component.html

<button type="button" (click)="loadModal()">Open Modal</button>

modal-component.ts

 @Output() messageEvent = new EventEmitter<string>();

private submit(){
let msg = "Test Message";
    this.messageEvent.emit(msg);
    this.bsModalRef.hide()
  }

modal-component.html

<button (click)="submit()">Submit</button>
like image 22
Udara Seneviratne Avatar answered Sep 20 '22 16:09

Udara Seneviratne