Angular Material: passing data to modal

Joshua Markasky
3 min readSep 8, 2021

So today we are going to be looking at a way to pass data to a modal. Lets start with the set up.

Set up is just a basic component called “ParentComponent” which is just a button that has a onclick event that calls the function “openModel”. Which then opens are pop up modal, which is just the component “UserFormComponent”. Which just says “User form works”. Simple enough, I go over how to get mat pop modals working on my last post I wrote so if that is confusing to you, I recommend reading that first.

The result of the code above. Ok, now lest pass some data to it.

The first way we are going to look at is by passing data to it with the “MatDialogConfig”. I explain what this is in our last post but basically, its a object with properties we can set to make changes to how the modal looks (width, height, ect). It also has a property called “data” that we can set. That, you guessed it, can be used to pass data to the modal.

Above you can see that we set .data to a object, which we just put some test data. Now lets go to the “UserFormComponent”, which is our modal, and add the code to catch this data.

In the constructor we pass a parameter “@Inject(Mat_Dialog_DATA) public data: any”. This catches the data in a var we can then user inside of the { } of our constructor. We then set a Var “FormParentComponent” and we set it to the value of the data we are passing. We are just console.log “this.formParentComponent” Var to make sure we are getting everything right.

Above you can see, when we open up our pop up modal, we can read in the console the data we are passing. So we are correctly passing data from the “ParentComponent” to our pop modal. Now you can always pass data between components using a service but I'm not going to go over that right now.

Hope that’s was helpful!

Connect with me on linkedIn: www.linkedin.com/in/joshua-markasky47

follow me on Twitter: https://twitter.com/MarkaskyJ

Checkout my YouTube channel: https://www.youtube.com/channel/UCgRkJcniRghYpSpzKQlEYvQ

--

--