Using MdDialogConfig data on Angular 2

前端 未结 3 1899
深忆病人
深忆病人 2021-01-13 10:37

I\'m trying to use a dialog component in Angular 2 using @angular/material2.0.0-beta.1. What I\'m trying to accomplish is to send data (which are values that a

3条回答
  •  攒了一身酷
    2021-01-13 11:11

    In parent component:

    const config = new MdDialogConfig();
    
    config.data = [
      // for example:
      'value 1',
      'value 2'
    ];
    
    const dialogRef = this.dialog.open(DialogComponent, config);
    

    DialogComponent:

    import { Component, OnInit } from '@angular/core';
    import { MdDialogRef }       from '@angular/material';
    
    @Component({
      selector: 'dialog',
      template: require('./dialog.component.pug'),
      styleUrls: [
        './dialog.component.scss'
      ]
    })
    export class DialogComponent implements OnInit {
      private values;
    
      constructor(public dialogRef: MdDialogRef) {}
    
      ngOnInit(): void {
        this.values = this.dialogRef.config.data;
      }
    }
    

    And sample template (HTML version):

    
      
        {{ value }}
      
    
    

    Update — @angular/material 2.0.0-beta.3

    Since version 2.0.0-beta.3 of Angular Material, it is no longer possible to access config (and config.data) property of MdDialogRef. Instead, you should inject MD_DIALOG_DATA token to access any data passed into your dialog component.

    Imports:

    import { Component, Inject, OnInit, Optional } from '@angular/core';
    import { MD_DIALOG_DATA, MdDialogRef }         from '@angular/material';
    

    The constructor:

    constructor(
      @Optional() @Inject(MD_DIALOG_DATA) private dialogData: any,
      private dialogRef: MdDialogRef
    ) {}
    

    ngOnInit method:

    ngOnInit(): void {
      // alternatively, rename ‘dialogData’ to ‘values’ and remove the
      // ‘ngOnInit’ method
      this.values = this.dialogData;
    }
    

    In many cases you’ll need to keep the @Optional() decorator, until issue 4086 will get resolved.

提交回复
热议问题