Angular Material Dialog Component

Manav Pandya  Print 
04 Oct 2018
 
Intermediate
405

In this part of angular material dialog component, we are going to learn that how to use dialog, how to integrate dialog with our angular application, passing data from dialog to our components etc. The dialog is one of the widely used elements which are used to get the quick values from the end-users, and when they completed with the form data, at a time dialog will be closed and the values of the dialog element will be processed.

The same way we can also use dialog component of angular material into our angular application.To integrate and use dialog component we need to take care of few things before getting started using dialog in our angular application, so let’s implement and use simple dialog step by step.

Simple Dialog

In our first example, we are going to use simple material dialog and for that, we need to follow few steps described below.

Step 1

In order to use the dialog component, we need to import it into the app module like this.

App.module.ts
 
import { MatDialogModule } from '@angular/material/dialog';

And then include it inside import array like this.

 
imports: [
 CommonModule,
 MatCardModule,
 MatDialogModule
 ]

Now we can use the dialog module in our angular application.

Step 2

We have imported dialog module in our root module file, now to open the dialog; we need to create dialog body so that we can show something on button click event.For that we need to create new component and implement dialog body inside the same component.

simpleDialog.component.ts
 
import { Component } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
 template: `
 <h1 mat-dialog-title>Hello There</h1>
 <div mat-dialog-content>
 <p>This Is a Simple Dialog</p>
 </div>
 <div mat-dialog-actions>
 <button mat-button (click)="close()">Close</button>
 </div>
`
})
export class SimpleDialogComponent {

 constructor(
 public dialogRef: MatDialogRef<SimpleDialogComponent>) { }

 close(): void {
 this.dialogRef.close();
 }
}

In the above source code, I have implemented a few things.

  • Created reusable dialog file so that we can include the same file at multiple places

  • Designed modal dialog body with title, content and action button to close the dialog box

  • I have used MatDialogRef which emits the event when dialog will be opened.

  • And created a simple dialog close event which is used to close the dialog when the user clicks on a close button presented inside dialog component.

Step 3

We have created dialog body as a separate component, but to use it inside any other component; we need to add it inside “entrycomponent”.The reason is that the dialog component will not be loaded when our angular application rendered into the browser, but dialog component will be added later into DOM when we try to open, in short, our dialog component will be rendered later on.For that open App.module.ts file and add it like this.

App.module.ts

First, we need to import it like this.

 import { SimpleDialogComponent } from './dialog-component/simpleDialog.component';
Then add it into declaration like this.
 declarations: [
 AppComponent,
 SimpleDialogComponent,
 ],

And also we need to specify inside entryComponents array something like this.
 entryComponents: [
 SimpleDialogComponent,
 ],

Step 4

Now let’s use our simple dialog box into our app component and see that how it works eventually.

App.component.ts
 
import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDialogConfig } from '@angular/material';
import { SimpleDialogComponent } from './simpleDialog.component';

@Component({
 selector: 'app-dialog-component',
 templateUrl: './dialog-component.component.html',
 styleUrls: ['./dialog-component.component.css']
})
export class DialogComponentComponent implements OnInit {

 simpleDialog: MatDialogRef<SimpleDialogComponent>;

 constructor(private dialogModel: MatDialog) { }

 ngOnInit() {
 }

 dialog() {
 this.simpleDialog = this.dialogModel.open(SimpleDialogComponent);
 }

}

Let’s break down all the important things what I have implemented.

  • In the app component, I have imported the dialog component which we have created previously

  • Then I have used dialog reference to our simple dialog component

  • Using MatDialog API, I am going to open our Simple Dialog component in which we have developed our dialog body, in short, we are calling dialog component indirectly from app component

Step 5

We have covered all the important steps to create and use dialog component, now it’s time to call the dialog component on button click from our app component.

App.component.html
 <mat-card>
 <div class="alert alert-info">
 <strong>Angular Material Dialog Component</strong>
 </div>
</mat-card>
<mat-card>
 <h2>Simple Dialog With Action Button</h2>
 <button mat-raised-button (click)="dialog()">Click Me To Open Dialog</button>
</mat-card>

In above HTML code, simply we are calling dialog () method which we have implemented into an app.component.ts file.

Step 6

Our last step is to execute the above example and see that how it works.Run angular app by using npm command npm start and output will look like this.When we run the example before click event.

And when we click on the button, at a time our dialog component will appear like this.

This is how we have implemented simple dialog box as a reusable component and called from the root component to open a simple dialog box in action, Now it’s time to add more flavors by adding some form fields to see that how dialog works with data.

Dialog with Form

Now everybody knows that how to use simple dialog component with our angular application, in this example, we are going to use a form with submitting an event using dialog component. For that, you need to follow few steps to achieve the same.

Step 1

Our first and primary step is to create a component for dialog which contains code for a form with different form fields.For this example, I am going to ask for two different value First name and last name from the user using a dialog box.Create a new component named dialogWithForm.

dialogWithForm.component.ts
import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

export interface DialogData {
 firstName: string;
 lastName: string;
}

@Component({
 template: `
 <h1 mat-dialog-title>
 Fill Basic Details
 </h1>
 <div mat-dialog-content>
 <mat-form-field>
 <input placeholder="First Name" matInput [(ngModel)]="data.firstName">
 </mat-form-field><br>
 <mat-form-field>
 <input placeholder="Last Name" matInput [(ngModel)]="data.lastName">
 </mat-form-field>
 </div>
 <div mat-dialog-actions>
 <button mat-button [mat-dialog-close]="data">Submit</button>
 <button mat-button (click)="onNoClick()">Close</button>
 </div>
})
export class DialogWithFormComponent {

 firstName: string = '';
 lastName: string = '';

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

 onNoClick(): void {
 this.dialogRef.close();
 }
}

Let me clarify all the implemented things into the above source code.Imported related things like :

  • Dialog reference : To get the reference of dialog to open and close it.

  • MatDialog : A class, which is used to work with a dialog component.

  • MAT_DIALOG_DATA : It is the very important part which is used to get the data from the dialog component and can pass it to another component.

If you observe the constructor, where I have used reference of dialog to close the dialog box, and also use @inject, it means that whenever user fills the data inside the dialog box with the form data, it will be injected and data will be forwarded to the calling component.

Step 2

Next step is to add our form component into app module as well as in entryComponents array like this.

App.module.ts

Import it like this inside module file.

import { DialogWithFormComponent } from './dialog-component/dialogWithForm.component';

Then add it to two different arrays, the first one is inside declaration [] array and than entryComponents [] array.

declarations: [
 AppComponent,
 DialogWithFormComponent,
 ],
entryComponents: [
 DialogWithFormComponent,
 ],

Step 3

Now let’s open the model from our root component and enter the form data presented inside dialog with form controls.

App.component.html
 <mat-card>
 <div class="alert alert-info">
 <strong>Angular Material Dialog Component</strong>
 </div>
</mat-card>
<mat-card>
 <h2>Dialog With Form</h2>
 <button mat-raised-button (click)="dialogForm()">Click Me To Open</button>
 <br>
 <ng-template [ngIf]="firstName && lastName">
 <h2>First Name IS : {{ firstName }}</h2>
 <h2>Last Name IS : {{ lastName }}</h2>
 </ng-template>
</mat-card>
App.component.ts
import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDialogConfig } from '@angular/material';
import { DialogWithFormComponent } from './dialogWithForm.component';

@Component({
 selector: 'app-dialog-component',
 templateUrl: './dialog-component.component.html',
 styleUrls: ['./dialog-component.component.css']
})
export class DialogComponentComponent implements OnInit {

 firstName: string;
 lastName: string;
 dialogConfig: MatDialogConfig;
 dialogWithForm: MatDialogRef<DialogWithFormComponent>;

 constructor(private dialogModel: MatDialog) { }

 ngOnInit() {
 }

 dialogForm() {

 // Opening the dialog component
 const dialogWithForm = this.dialogModel.open(DialogWithFormComponent, {
 width: '250px',
 data: { firstName: this.firstName, lastName: this.lastName }
 });

 // When user close the dialog
 dialogWithForm.afterClosed().subscribe(result => {
 console.log('You have closed the dialog');
 if (result) {
 this.firstName = result.firstName;
 this.lastName = result.lastName;
 }
 });
 }

}

Let’s break down all the functionality we have implemented into the above source code.

  1. Imported our dialog component which contains the form

  2. Declared two different variables for first name and last name to hold form values and print it inside our app component output

  3. Inside the dialog Form() method :

    • Going to open a dialog box with the data parameter which holds the value of two variables which we have declared previously

    • And when the user closes the dialog, at a time afterClose() event will be triggered and we will get the data into two variables into the form of result

Step 4

So far, we have implemented all the things which we intended to develop, the next step is to execute the above example and see the action.When you run the example, it will look like this.

Click on the button and can see the dialog appeared like this.

Just provide the different values for first name and last name, then click on the submit button, it will close the dialog and we will have both the values like this.

As you can see into above image that we got the two different values added by us inside a model dialog and in output we have values which coming from the dialog component. This is how we can implement a form with different form fields, you can expand it by using different form fields like radio buttons, dropdowns, and file uploads.

Summary

In this part of angular material series, we have covered different things which are listed below.

  • How to integrate and use an Angular material dialog component

  • Use forms with different form fields, and passing the data between the components

    I hope now you have an idea that how to integrate Dialog component with our angular application and play with it. Thanks for reading.

Crack Your Technical Interview

 
Join Our Hands-on Training Programs

+