Search code examples
angularangular7angular-material-table

How to get data in mat-cell and display in dialog form Angular 7?


I am trying to make a mat-cell clickable and display form fields inside a mat-dialog and populating those fields with the data inside the mat-cell.

enter image description here

That is the current display that I have but I want it to be beside the mat-cell where it was clicked.

Here is the code in stackblitz. https://stackblitz.com/edit/angular-akbfr8

Any help will do. Thanks.


Solution

  • You need to pass the data to the modal using the data property on the config object.

    let dialogRef = dialog.open(YourDialog, {
      data: { name: 'austin' },
    });
    

    You can then use that data by injecting it into the Modal's constructor like so:

    import {Component, Inject} from '@angular/core';
    import {MAT_DIALOG_DATA} from '@angular/material';
    
    @Component({
      selector: 'your-dialog',
      template: 'passed in {{ data.name }}',
    })
    export class YourDialog {
      constructor(@Inject(MAT_DIALOG_DATA) public data: { name: string }) { }
    }
    

    You can read more about it in the docs: https://material.angular.io/components/dialog/overview#sharing-data-with-the-dialog-component-


    To have the dialog appear next to the cell that opened it you will need to set the position of the dialog. To do that define the left and top properties of the position property in the config object to be the right side of the cell.

    dialog.open(YourDialog, {
      position: {
        left: `${cellElement.offsetLeft + cellElement.offsetWidth}px`,
        top: `${cellElement.offsetTop + cellElement.offsetHeight}px`,
      }
    })
    

    I have updated your stackblitz to demo this behavior.

    Stackblitz