简体   繁体   English

angular中的material dialog组件如何调用另一个组件的方法 14

[英]How to call a method in another component from material dialog component in angular 14

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组分A

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组件B.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?当在componentB.dialog中调用cancle() 时,如何调用 methodToBeCalledFromCompB()

You should be able to do this with a callback function , although it's not elegant.您应该可以通过回调 function来执行此操作,尽管它并不优雅。 When you open the dialog, you would pass a reference to methodToBeCalledFromCompB(), and then within the dialog invoke that function.当您打开对话框时,您将传递对 methodToBeCalledFromCompB() 的引用,然后在对话框中调用该 function。

Another way to do this is to make/use a global service class for componentA that triggers the method in componentA.另一种方法是为 componentA 创建/使用全局服务 class 触发 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.将服务注入 componentB 对话框,然后调用服务的方法,该方法向 componentA 发出一个事件,告诉它调用该方法。

In componentB.dialog and componentA constructors, import the service constructor(aService: ComponentAService)在 componentB.dialog 和 componentA 构造函数中,导入服务constructor(aService: ComponentAService)

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

In componentA.service,在componentA.service中,

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

emitMethod() {
   eventEmitter.emit();
}

In componentA,在组件A中,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM