How to pass data to a MatDialog

Tom

October 9, 2020

If you’re new to using Angular Material one of the issues you’re bound to encounter at some point is how to provide data to a MatDialog and use it in the opened component.

The TL;DR

You can pass any kind of data to the component by adding data to the MatDialog’s open() options.

this.dialog.open(PersonalDetailsComponent, {
   data: {
       person: {
           name: ‘Simon’,
           age: 32,
       }
   },
});

You can retrieve the data by injecting MAT_DIALOG_DATA in the opened component.

constructor( @Inject(MAT_DIALOG_DATA) public data: IPerson ) {
}


Solution

The solution is simple, but a little more obscure than other implementations in Angular Material so I have written this as a quick reference guide for anyone trying to achieve this for the first time, or just needs a quick reminder of the implementation.

opens-dialog.component.ts

constructor(private readonly dialog: MatDialog) {
}
openPersonalDetailsDialog(): void {
   this.dialog.open(PersonalDetailsComponent, {
               width      : '100%',
               maxWidth   : '400px',
               height     : 'auto',
               hasBackdrop: true,
               maxHeight  : '700px',
               panelClass : ‘personal-details-dialog‘,
               data       : {
                   person: {
                       name: ‘Simon’,
                       age: 32,
                   }
               },
   });
}


As you can see, passing data to a dialog component is as simple as adding a data key to the options parameter of the dialog.open() method. You can pass as many keys and values as you deem necessary into the opened dialog.

So how do I access this data in my PersonalDetailsComponent? Easy! You just need to make sure you add the following injection into your constructor of the component being opened by the dialog.

personal-details.component.ts

constructor( @Inject(MAT_DIALOG_DATA) public data: IPerson ) {
}

You can then use this like any other imported service, data etc in your component. Bare in mind, this value will be undefined if you use the component in a non-dialog context (<app-personal-details></app-personal-details> for example) so if you plan on using it in multiple ways, you should amend your code to handle this accordingly.

personal-details.component.ts

logAge(): void {
   console.log( this.data.age );
}

personal-details.component.html

<p>Hello, I am {{ data.name }}, and I am {{ data.age }} years old!</p>

Simple as that!

Tom

Tom

A Web, Tech, Football and Video Game enthusiast. Anything can be settled in smash! I’m a Software Engineer on the nerd.vision team with various front-end and back-end skills.