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

前端 未结 5 1621
眼角桃花
眼角桃花 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条回答
  •  不知归路
    2020-12-24 11:20

    Material2 beta.2

    The dialog.open() function takes a 2nd parameter config (MdDialogConfig) where you can specify any data object.

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

    You can then just retrieve this object from the component that is being used for your dialog window.

    export class YourDialogComponent {
    
      constructor(public dialogRef: MdDialogRef) {
        console.log('data', this.dialogRef.config.data);
      }
    }
    

    UPDATE: beta.3

    The answer above works for the version 2.0.0-beta.2 of Material2. If you are using 2.0.0-beta.3, the config property was removed from MdDialogRef. you can instead inject that value using the MD_DIALOG_DATA of the opened component.

    New import statements

    import {MdDialog, MdDialogRef, MdDialogConfig, MD_DIALOG_DATA} from '@angular/material';
    

    OPEN DIALOG

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

    RETRIEVE DATA FROM DialogRef component

    export class YourDialogComponent {
    
      constructor(
        public dialogRef: MdDialogRef,
        @Inject(MD_DIALOG_DATA) public data: any) {
    
        console.log('data', this.data);
      }
    }
    

提交回复
热议问题