Make sure to include the following code in your app.module.ts
file:
import {MatDialogModule} from '@angular/material/dialog';;
...
@NgModule({
declarations: [
...
],
imports: [
...
MatDialogModule,
],
Import the necessary components in your component's TypeScript file (.ts
):
import {Component, Inject} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
export interface DialogData {
animal: string;
name: string;
}
@Component({
selector: 'dialog-overview-example',
templateUrl: 'dialog-overview-example.html',
})
export class DialogOverviewExample {
animal: string;
name: string;
constructor(public dialog: MatDialog) {}
openDialog(): void {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '250px',
data: {name: this.name, animal: this.animal}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
this.animal = result;
});
}
}
@Component({
selector: 'dialog-overview-example-dialog',
template: `
<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
<p>What's your favorite animal?</p>
<mat-form-field>
<mat-label>Favorite Animal</mat-label>
<input matInput [(ngModel)]="data.animal">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">No Thanks</button>
<button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
</div>`,
})
export class DialogOverviewExampleDialog {
constructor(
public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) {}
onNoClick(): void {
this.dialogRef.close();
}
}
In your HTML file, add the following code to display the dialog and interact with it:
<ol>
<li>
<mat-form-field>
<mat-label>What's your name?</mat-label>
<input matInput [(ngModel)]="name">
</mat-form-field>
</li>
<li>
<button mat-raised-button (click)="openDialog()">Pick one</button>
</li>
<li *ngIf="animal">
You chose: <i>{{animal}}</i>
</li>
</ol>
Finally, start your server by running ng serve -o
.