Search code examples
angularangular-materialng-template

Angular 14 - Getting data out of angular material dialog


I'm looking to get data out from my material dialog that uses a ng-template. I'm getting a Property 'data' does not exist on type 'MeetingsComponent'. when trying to use this line.

<button mat-raised-button [mat-dialog-close]="data" cdkFocusInitial>Save</button>

This is my full code for the template:

<ng-template #editMeeting>
    <mat-dialog-content>
        <mat-form-field appearance="outline">
            <mat-label>Meeting Name</mat-label>
            <input #name matInput type="text" autocomplete="off"/>
        </mat-form-field>
        <mat-form-field appearance="outline">
            <mat-label>Meeting Location</mat-label>
            <input #location matInput type="text" autocomplete="off"/>
        </mat-form-field>
        <mat-form-field appearance="outline">
            <mat-label>Choose a date</mat-label>
            <input #date matInput [matDatepicker]="picker">
            <mat-hint>MM/DD/YYYY</mat-hint>
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
    </mat-dialog-content>
    <div mat-dialog-actions>
        <button mat-raised-button mat-dialog-close>Close</button>
        <button mat-raised-button [mat-dialog-close]="data" cdkFocusInitial>Save</button>
    </div>
</ng-template>

This line is called to open dialog:

<button mat-raised-button type="button" (click)="edit(editMeeting, row)">Edit</button>

And this is the edit function being called:

  edit(content: any, row: any): void {
    this.matDialog.open(content, {
      data: {name: row.name}
    })
    console.log(row)
  }

I know this isn't the best way to render dialog content, but just for speed right now, this is the way I'm doing it. Let me know if I left out any needed code.


Solution

  • In your dialog component, you need to declare data object to receive from parent in component's constructure.

    constructor(@Inject(MAT_DIALOG_DATA) public data: any) { ...}
    

    Full example: Stackblitz