How can I pass a service variable into an Angular Material dialog?

前端 未结 5 1612
眼角桃花
眼角桃花 2020-12-24 10:40

For mdDialog, how do I pass in variable? Specifically, how to inject an Angular service into the dialog component?

5条回答
  •  梦毁少年i
    2020-12-24 11:30

    To give an updated answer to accommodate for the update from 'Md' to 'Mat':

    • This assumes you already have a dialog successfully implemented and are now just looking to add an input
    • This is the solution when you are having an issue that @angular/material has no exported member 'MD_DIALOG_DATA'

    To open the dialog with data, pass in a data object:

    this.dialog.open(YourComponent, {
      data: {
        anyProperty: "myValue"
      }
    });
    

    To retrieve that data in your dialog:

    import { Component, Inject } from '@angular/core';
    import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
    
    export class YourDialogComponent {
    
      constructor(
        public dialogRef: MatDialogRef,
        @Inject(MAT_DIALOG_DATA) public data: any) {
    
        console.log('data passed in is:', this.data);
      }
    }
    

提交回复
热议问题