Reputation: 121649
I'm trying to write a simple "yes/no" confirmation box in Angular 8.3.
In C#, Java, JS, etc etc it would be a one-liner: var result = MessageBox.Show("Click Me", "My Dialog", MessageBoxButtons.YesNo);
In Angular, it seems the preferred approach is to use a Material Dialog. It kind of works - but it doesn't look or behave like I would expect. Specifically:
Q: How can I do this?
NOTE: I like this link ... but it seems obsolete: https://stackoverflow.com/a/39106139/3135317
app.module.ts
import { MatDialogModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
...
import { ConfirmationDlgComponent } from './common/confirmation-dlg.component';
@NgModule({
declarations: [
...
ConfirmationDlgComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
...
MatDialogModule
],
providers: [],
entryComponents: [ ConfirmationDlgComponent ],
bootstrap: [AppComponent]
})
export class AppModule { }
confirmation-dlg.component.ts
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogConfig } from '@angular/material';
@Component({
template: `
<h3 mat-dialog-title>{{dlgTitle}}</h3>
<mat-dialog-content>{{dlgMessage}}</mat-dialog-content>
<mat-dialog-actions>
<button mat-button mat-dialog-close>No</button>
<button mat-button [mat-dialog-close]="true" cdkFocusInitial>Yes</button>
</mat-dialog-actions>
`
})
export class ConfirmationDlgComponent {
dlgTitle: string;
dlgMessage: string;
constructor(
public dialogRef: MatDialogRef<ConfirmationDlgComponent>,
@Inject(MAT_DIALOG_DATA) public extraData) {
this.dlgTitle = extraData.dlgTitle;
this.dlgMessage = extraData.dlgMessage;
}
}
list-contents.component.html
<button class="btn btn-primary" (click)="deleteContact(contact)"> Delete Contact </button>
list-contents.component.ts
deleteContact(contact: Contact) {
const dialogRef = this.dialog.open(ConfirmationDlgComponent, {
hasBackdrop: true,
height: '250px',
position: {top: '', bottom: '', left: '', right: ''},
data: {
dlgTitle: 'Delete (' + contact.name + ')',
dlgMessage: 'Really delete this contact?'
}
});
dialogRef.afterClosed().subscribe(result => {
if(result) {
console.log('Yes clicked');
this.contactsService.deleteContact(contact).subscribe(
data => {
console.log('loadContacts', data);
this.loadContacts();
},
err => {
console.error('deleteContact', err);
});
}
});
}
Upvotes: -1
Views: 2857
Reputation: 121649
All I had to do was add this line to styles.css
:
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
From this link:
https://appdividend.com/2019/02/11/angular-modal-tutorial-with-example-angular-material-dialog/
Upvotes: 1