Use your custom component inside Angular Material Dialog

Mariola Moreno González
MásMóvil Engineering
1 min readFeb 13, 2019

Angular Material offers us a set of useful components to use on a daily bases. One of them is Material dialog. If you read the Angular Material documentation, it doesn’t explain how to insert your own components into it.

Imagine you have a component (with inputs and outputs) and you want to show it inside a dialog. I will show you a solution that may be useful:

modal-material.component.html

modal-material.component.ts

You can use a component to be loaded inside the modal-material component and set inputs. It’s important to remember that you must load this custom component and the hosted one in module entryComponents:

Don’t forget to register this modal component, and the hosted one as ‘entryComponents’, in the module

With the code below, you can set the needed inputs to the hosted component and listen the outputs as well. Now that we have the component ready, you only have to open the dialog this way:

How to listen outputs from hosted component

You must subscribe to afterOpen() method from you dialogRef, and then you will have access to the componentInstance (you hosted component) outputs.

dialogRef.afterOpen()
.subscribe(() => {
const subs = dialogRef.componentInstance[‘myEmitter’]
.subscribe(() => { … }
})

Remember to unsubscribe all the current subscriptions

dialogRef.afterClose().subscribe(() => subs.unsubscribe())

What about testing?

This is my test for this new Angular Material Dialog feature:

I hope this post has been useful to you!! Thanks!

--

--