How to pass data to dialog of angular material 2

后端 未结 5 1116
花落未央
花落未央 2020-11-29 03:25

I am using dialog box of angular material2.

I want to pass data to the opened component. Here is how I am opening dialog box on click of a button

let         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 03:59

    I thought I'd give a fuller answer for those of us who are still learning:

    Unlike the Material Examples I configured the dialog to have its own component files (html, css and ts) for ease of debugging.

    Main component file "x.component.ts" (calling the dialog)

    1) add the import statement

    import { MatDialog} from '@angular/material';
    

    2) add the property to the constructor params

    public dialog: MatDialog
    

    3) define the code to call the dialog box

      openDialog(title: string, text: string): void {
    const dialogRef = this.dialog.open(DialogComponent, {
      width: '350px',
      data: {dialogTitle: title, dialogText: text}
    );
    
    dialogRef.afterClosed().subscribe(result => {
    });
    
      const dialogSubmitSubscription = 
      dialogRef.componentInstance.submitClicked.subscribe(result => {
      dialogSubmitSubscription.unsubscribe();
    });
    

    }

    Call the function from your html file with openDialog(). I'm referencing DialogComponent so make sure its imported into your module.

    import { DialogComponent } from './dialog/dialog.component';
    

    also

    entryComponents: [DialogComponent]
    

    declare it in your entryComponents array

    4) in your dialog.component.ts file, add the imports

    import { Component, Output, EventEmitter, Inject, OnInit} from '@angular/core';
    import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
    

    5) define the properties & functions

    dialogTitle: string;
    dialogText: string;
    @Output() submitClicked = new EventEmitter();
    
      constructor(
        public dialogRef: MatDialogRef,
        @Inject(MAT_DIALOG_DATA) public data: DialogData) {}
    
    
      ngOnInit() {
        this.dialogTitle = this.data.dialogTitle;
        this.dialogText = this.data.dialogText;
      }
    
      saveMessage() {
        const data = 'Your data';
        this.submitClicked.emit(data);
        this.dialogRef.close();
      }
    
      closeDialog() {
        this.dialogRef.close();
      }
    

    6) and lastly the HTML

    {{dialogTitle}}"

    {{dialogText}}

    I hope it helps.

提交回复
热议问题