Implementing Modal/Dialog using Angular/Material in Angular 9

Implementing dialog box is pretty easy with angular/material and it provides a lot of handy features. We can pass data to the Dialog box and depending upon user response. so let’s get started.

We need two components to implement this one say app.component from where we will open this modal and second component if modal itself.

First let’s create Modal Component

Here ProgressData class can be used to specify fields which we need in this component or we simply pass data from app.component.ts which we will see later.

here we can see on clicking yes button (click) listener will call onConfirm() method which in turn emits true and No button eventually leads to emitting false.

Components created via MatDialog can inject MatDialogRef and use it to close the dialog in which they are contained.

Because MatDialog instantiates components at runtime, Angular needs extra information to create necessary components. That’s where entryComponents array kicks in. we have to specify all the components which are not loaded by routing or by their template like <app-login> in entryComponents array.

now let’s talk about the app component from where we can call this and listen to events.

We can send the data using an object like width, height, data, and many other properties. Then dialogRef.afterClosed() return an Observable to which we can subscribe to listen to events that may occur in the future. Angular uses a lot of observables. Depending on the response we can perform our required task.

That’s all we have built this modal using Angular material.

Frontend engineer who loves the Web, JavaScript and Angular.