import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
@Component({
selector: 'app-alert-dialog',
templateUrl: './alert-dialog.component.html',
styleUrls: ['./alert-dialog.component.css']
})
export class AlertDialogComponent {
constructor(public dialogRef: MatDialogRef,
@Inject(MAT_DIALOG_DATA) public data: any) {
console.log(data);
}
onOKClick(): void {
this.dialogRef.close();
}
}
- The HTML file would be:
{{data.message}}
- Once the component is completed, we need to add it in a module. If this is use in the whole project, import it in the root module.
...;
import {AlertDialogComponent} from "@app/shared/alert-dialog/alert-dialog.component";
export const appConfig = {
declarations: [
...,
AlertDialogComponent
],
imports: [
...,
],
entryComponents:[
...,
AlertDialogComponent],
providers: [...],
bootstrap: [AppComponent]
- To use the alert dialog in your component, import it:
...;
import {AlertDialogComponent} from "@app/shared/alert-dialog/alert-dialog.component";
import {MatDialog} from "@angular/material";
- Then inject a MatDialog in your component constructor:
constructor(public dialog: MatDialog) {}
- To show up the dialog, call this code:
const dialogRef = this.dialog.open(AlertDialogComponent, {
width: '250px',
data: {message: "OK, Jahaa, sehr gut!"}
});
- Note: we use ''date.message'' to pass the message to our alert dialog component. Go back to step 3 and 4, you will see how to dialog get that ''date''.
{{ :ng:ng_alert_dialog.png?nolink&200 |}}
===== Dialog with Response =====
- Do all the thing like the basic dialog
- Modify the HTML of your component so that use can do some input, bind that input to a variable in your ts file.
- The ''component that open the dialog'' should subscribe the dialog afterClosed event as below. The ''result'' would be what the dialog component pass to the subscriber
dialogRef.afterClosed().subscribe(result => {...});
- In the ''dialog component'', when you close it, close it with a parameter of any kind you like. that would be what the subscriber receives as the ''result'' variable. In the below case, the subscriber will receive a number of 10.
this.dialogRef.close(10);