Mohsine Jirou
Mohsine Jirou

Reputation: 11

Angular - How to call a modal in a component from another component?

I am trying to call a modal (created with Mdbootstrap) in a component from another component,but i struggle how to do it in Angular. Well this is the code of the modal : [editComponent.html] :

<div mdbModal #basicModal="mdbModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myBasicModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close pull-right" aria-label="Close" (click)="basicModal.hide()">
          <span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title w-100" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" mdbBtn color="secondary" class="waves-light" aria-label="Close" (click)="basicModal.hide()" mdbWavesEffect>Close</button>
        <button type="button" mdbBtn color="primary" class="relative waves-light" mdbWavesEffect>Save changes</button>
      </div>
    </div>
  </div>
</div>

And there is another component called [ProduitComponent.html ] where there is a button (Edit),once i click on the button the Modal should appear on the same page.

Thank you !

Upvotes: 1

Views: 754

Answers (1)

mwilson
mwilson

Reputation: 12900

You can only accomplish this in a handful of ways. If you are trying to execute code within a component from another component, you have to get a reference to said component. Then, you can access public properties/methods with ComponentRef<Component>.instance.

I would recommend moving your dialog (modal) to a DialogService of some sort so that you can easily invoke the dialog form any component you wish. Since mdbootstrap doesn't come with a pre-packaged out of the box dialog, you will probably have to create a BootStrapModalComponent and in your service, insert the dialog dynamically using the ComponentFactory

Example:

const componentFactory = ComponentFactoryResolver.resolveComponentFactory(MyBootstrapModalComponent);
ViewContainerRef.createComponent(componentFactory);

Then, in your service, you would have logic to run the Component Creation process when they call dialogOpen or something. When they call dialogClose, then you run similar logic that destroys the dialog.

IMO, the way the Angular Material team did the MatDialog/MatDialog` is much cleaner. They provide a CDK that you might be able to use to make your bootstrap modals more generic.

Another option is to take a poor-mans route and create a DialogService that just has an EventEmitter. That EventEmitter can be a singleton service that is shared across components to transmit your open/close events between any component. Although this would work without issue, it's not as elegant.

Upvotes: 1

Related Questions