0

I am wondering if there is a way to call a method in one component from a dialog component?

Here is it, having the first component to be:

componentA

openDialog(): void {
  const dialogRef = this.dialog.open(componentB.dialog, {
  width: '700px',
});

methodToBeCalledFromCompB() { //how to called this
  console.log('test');
}

The second component is

componentB.dialog

constructor(...) {}

public cancel() {
  
  //how do I call the method methodToBeCalledFromCompB() that is in **copmponetA** here before closing the dialog

  this.dialogRef.close();
}

How can I call methodToBeCalledFromCompB() when the cancle() is called in componentB.dialog?

Kent
  • 33
  • 7

1 Answers1

0

You should be able to do this with a callback function, although it's not elegant. When you open the dialog, you would pass a reference to methodToBeCalledFromCompB(), and then within the dialog invoke that function.

Another way to do this is to make/use a global service class for componentA that triggers the method in componentA. Inject the service into componentB dialog, then call the service's method, which emits an event to componentA telling it to call the method.

In componentB.dialog and componentA constructors, import the service constructor(aService: ComponentAService)

In componentB.dialog's cancel(), aService.emitMethod()

In componentA.service,

eventEmitter: EventEmitter<any> = new EventEmitter<any>();

emitMethod() {
   eventEmitter.emit();
}

In componentA,

this.aService.eventEmitter.subscribe((data: any) => {
      this.methodToBeCalledFromCompB();
});
theRavenCodes
  • 21
  • 1
  • 1