Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Angular7 Alert/Confirm service leveraging Material dialog
wraps alert/confirm logic, hiding underlying implementation for reuse.
/*
Usage: alert:
const dialogRef = this.alertHelper.showAlert(false,
"My message",
"My title");

Usage: confirm:
const dialogRef = this.alertHelper.showAlert(true,
"My message - do action?",
"My title - confirm");
dialogRef.afterClosed().subscribe(result => {
if(result)
alert('do action here');
});

alert.service.ts:

import { Injectable } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AlertConfirmComponent } from '../common/alertconfirm.component';

@Injectable({
providedIn: 'root'
})
// wraps alert/confirm logic, hiding underlying implementation for reuse.
/*
Usage: alert:
const dialogRef = this.alertHelper.showAlert(false,
"My message",
"My title");

Usage: confirm:
const dialogRef = this.alertHelper.showAlert(true,
"My message - do action?",
"My title - confirm");
dialogRef.afterClosed().subscribe(result => {
if(result)
alert('do action here');
});
* */
export class AlertService {
constructor(private alertHelper: MatDialog) { }

showAlert(isConfirm: boolean, message: string, title: string) {
if (title == null) title = "Alert";

const dialogRef = this.alertHelper.open(AlertConfirmComponent, {
width: '500px',
data: {
title: title, isconfirm: isConfirm, text: message
}
});
return dialogRef;
}
} // class


alertconfirm.component.ts:

import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
selector: 'alertconfirm',
templateUrl: './alertconfirm.component.html'
})
export class AlertConfirmComponent {

constructor(
public dialogRef: MatDialogRef<AlertConfirmComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) { }

onNoClick(): void {
this.dialogRef.close();
}
}
export interface DialogData {
title: string;
text: string;
isconfirm: boolean;
}

alertconfirm.component.html:

<h1 mat-dialog-title>{{data.title}}</h1>
<div mat-dialog-content>
<p>{{data.text}}</p>
</div>
<div mat-dialog-actions>
<button mat-button [mat-dialog-close]="true" cdkFocusInitial>Ok</button>
<button *ngIf="data.isconfirm" mat-button (click)="onNoClick()">Cancel</button>
</div>

Created By: amos 1/16/2020 9:59:47 AM