Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular mat-dialog undefined value afterClosed()

i have been working in a project with angular 5 and angular material, i´m tryng to pass value to dialog and get the value back when the dialog is closed, but for some reason i´m getting undefined when the dialog is closed.

Dialog

import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ReaderService } from '../../../../../services/reader/reader.service';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
  selector: 'fuse-comment-dialog',
  templateUrl: './comment-dialog.component.html',
  styleUrls: ['./comment-dialog.component.scss']
})
export class CommentDialogComponent implements OnInit {

  public commentsForm: FormGroup;
  constructor(
    private fb: FormBuilder,
    private readerService: ReaderService,
    public dialogRef: MatDialogRef<CommentDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) { }

  ngOnInit() {
    this.commentsForm = this.fb.group({
      commentText: ['', [
        Validators.required
      ]],
      commentType: 'PrivateComment',
      commentGroup: 'Therabytes'
    });
  }

  public sendComent(): void {
    this.data['text'] = this.commentsForm.value.commentText;
    this.data['commentVisibility'] = this.commentsForm.value.commentType;
    this.readerService.newComment(this.data)
      .then((commentId) => {
        this.data['id'] = commentId;
        this.dialogRef.close();
      });
  }

  public closeDialog(): void {
    this.commentsForm.value.commentText = '';
    this.dialogRef.close();
  }

}

Comment Component

public commentDialog(): void {
    let newComment = {
      documentId: this.document.id
    };
    let commentDialogRef = this.dialog.open(CommentDialogComponent, {
      width: '300px',
      data: newComment
    });
    commentDialogRef.afterClosed().subscribe(comment => {
      console.log(comment);
      this.comments.push(comment);
    });
  }
like image 974
Miguel Frias Avatar asked Dec 08 '22 14:12

Miguel Frias


2 Answers

In order to get the data from your modal to your afterClosed() Observable, you need to pass an argument to your dialogRef.close() method as follows:

this.dialogRef.close(this.data);
like image 70
TheUnreal Avatar answered Dec 28 '22 06:12

TheUnreal


This issue had me stumped for a while.

Assuming that you've already tried the accepted answer and still have issues, please ensure that you inject MatDialogRef, instead of DialogRef.

like image 43
Stephen Paul Avatar answered Dec 28 '22 08:12

Stephen Paul