Develop common Dialog Box Service using Angular 7

旧巷老猫 提交于 2019-12-04 20:51:10

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!

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

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