Develop common Dialog Box Service using Angular 7

老子叫甜甜 提交于 2019-12-06 15:17:57

问题


I am working on Angular 7 and looking to develop common component or service to show Alerts/Dialog Box when User Confirming/Deleting details on button click.

I went through link: https://firstclassjs.com/create-a-reusable-confirmation-dialog-in-angular-7-using-angular-material/ and on web I found the many people are using Angular Material way to implement.

Is there any simple way to dynamically pass the title and message to alert service or component based on action like Update/Delete you're performing?


回答1:


In app.component.ts you need to extend openDialog() like this:

openDialog(title: string, message: string): void {
    this.title = title;
    const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
      width: '350px',
      data: message,
    });
    dialogRef.afterClosed().subscribe(result => {
      if(result) {
        console.log('Yes clicked');
        // DO SOMETHING
      }
    });
  }

And extend (app.component.html) like this:

<button mat-button (click)="openDialog('I am the Title', 'I am the content-message ')">Confirm box</button>

Good luck!




回答2:


I assume you follow the link you provided.

  • add a new service like confirmDialogService
  • Service will have an observable like openDialog$: Subject<{title: string, message: string}> = new Subject<{title: string, message: string}>();
  • Service will have a method called openConfimDialog(string message, string title) { this.openDialog$.next({title, message}) };
  • Inject this service in App.Component and subscribe to openDialog$, then inside subscription call openDialog() method from link you provided and also pass message and title to the dialog
  • Inject the service in the component you want and call openConfirmDialog

at this point you should be able to see the dialog will be opened.

next step is to receive if the user confirm or cancel dialog.

use the same pattern to have another observable afterClosed$ in service and a method to called notifyDialogClosed

now this time call notifyDialogClosed from app.component and subscribe to afterClosed$ in your component, just don't forget to unsubscribe

If you create stackblitz of that link you provided I can help you for the rest



来源:https://stackoverflow.com/questions/58272140/develop-common-dialog-box-service-using-angular-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!