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?
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