4

I am trying to pass data from a Dialog back to the component from which the user opened the dialog from. My simple example is below:

test.component.ts

import { xDialogComponent } from './../x-dialog/x-dialog.component';
import { xFilter } from './x-filter';
import { xLevelResult, xmodelResult, xpayResult, xpayClassResult, xSpResult } from './../database.service';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { databaseService, xSigResult, xOutResult, CurxpayResult } from '../database.service';
import { HttpClient } from '@angular/common/http';
import { NgIf } from '@angular/common/src/directives/ng_if';
import { element } from 'protractor';
import { ActivatedRoute } from '@angular/router';
import { MakeGroup, xpayteamResult, xpayteamSPResult, NoticeResult } from '../database.service';
import { DateResult } from '../database.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import {MatSortModule} from '@angular/material/sort';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule, MatCheckboxModule} from '@angular/material';
import {MatTabsModule} from '@angular/material/tabs';
import {Observable, forkJoin} from 'rxjs';
import {mergeMap, expand, map, flatMap, concat, switchMap, combineAll} from 'rxjs/operators';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatFormFieldModule} from '@angular/material/form-field';
import { MatInputModule, MatTableModule, MatPaginatorModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import {MatSnackBar} from '@angular/material';
import { MakeService } from './../../Make.service';
import {MatDialogModule} from '@angular/material/dialog';
import {MatDialogRef, MAT_DIALOG_DATA, MatDialog} from '@angular/material/dialog';



@Component({
  selector: 'app-x',
  templateUrl: './x.component.html',
  styleUrls: ['../style.css']
})
export class xComponent implements OnInit {

  MakeGroups: MakeGroup[];
  xLevelresults: Array<xLevelResult>;
  xmodelresults: Array<xmodelResult>;
  xsigresults: Array<xSigResult>;
  curxpayresults: Array<CurxpayResult>;
  xpayresults: Array<xpayResult>;
  xpayclassresults: Array<xpayClassResult>;
  xpayteamresults: Array<xpayteamResult>;
  xpayteamspresults: Array<xpayteamSPResult>;
  FinalArray: any[] = [];
  x_sp_results: Array<xSpResult>;
  noticeresults: Array<NoticeResult>;
  modelName: string;
  TransactionDate: string;
  MakeName: string;
  delete: string;
  dateselect: string;
  noticedays: number;
  selectedEffect: number;


  // Disablers
  SubmitDisabled: boolean;
  AmountDisabled: boolean;
  DateDisabled: boolean;
  ISDisabled: boolean;
  modelDisabled: boolean;
  SigDisabled: boolean;
  editswitch: boolean;
  nextswitch: boolean;


  // Selection variables for SP Call
  selectedLevel: number;
  selectedAmount: number;
  selectedmodelNbr: number;
  selectedClassId: number;
  Advteam_DRAW_REPAY: number;
  selectedSigId: number;

  // SP Call
  xspcall: string;

  // Date variables
  date: Date;
  selectedDate = '';
  success: boolean;
  tomorrow: number;
  yformat = '';


  // x Outstanding
  xoutresults: Array<xOutResult>;
  x: number;

  constructor(
    private databaseService: databaseService,
    private route: ActivatedRoute,
    private router: Router,
    private MakeService: MakeService,
    public dialogx: MatDialog,

    public snackBar: MatSnackBar
  ) {}


// changes the actual value of the variable for selectedLevel based on user selection
changedLevel (xLevelresult: xLevelResult) {
  // Disable to ensure user enters correct data
  this.SubmitDisabled = true;
  this.DateDisabled = true;
  this.SigDisabled = true;
  this.xpayresults = [];
  this.xsigresults = [];
  this.selectedDate = undefined;
  this.selectedSigId = undefined;
  this.xpayclassresults = [];
  this.xpayteamresults = [];
  this.xpayteamspresults = [];
  this.curxpayresults = [];
  this.FinalArray =  [];
  this.selectedAmount = undefined;
  this.selectedLevel = (xLevelresult ? xLevelresult.Make_Level_Id : 1);
  console.log(this.selectedLevel);
// Populate model Drop-Down
const id = this.route.snapshot.paramMap.get('id');
this.databaseService.getxmodel(id, this.selectedLevel)
  .subscribe(xmodelresults => this.xmodelresults = xmodelresults);
}

// changes the actual value of the variable for selectedmodelNbr based on user selection
changedmodel (xmodelresult: xmodelResult) {
  this.SubmitDisabled = true;
  this.DateDisabled = true;
  this.SigDisabled = true;
  this.selectedDate = undefined;
  this.xpayresults = [];
  this.xsigresults = [];
  this.selectedSigId = undefined;
  this.xpayclassresults = [];
  this.xpayteamresults = [];
  this.xpayteamspresults = [];
  this.curxpayresults = [];
  this.FinalArray =  [];
  this.selectedAmount = undefined;
  this.selectedmodelNbr = (xmodelresult ? xmodelresult.model_Nbr : 1 );

  console.log(this.selectedmodelNbr);
}



// // changes the actual value of the variable for selectedAmount based on user selection
changedAmount (event: any) {

  if (this.editswitch === true) {
    this.SubmitDisabled = true;
    this.DateDisabled = true;
    this.selectedAmount = event.target.value;
    this.xpayresults = [];
    this.xpayclassresults = [];
    this.xpayteamresults = [];
    this.xpayteamspresults = [];
    this.curxpayresults = [];
    this.FinalArray =  [];
    const id = this.route.snapshot.paramMap.get('id');
    // change all values
    this.selectedDate = this.xoutresults[this.x].Calc_Dt;
    this.selectedLevel = this.xoutresults[this.x].Make_Level_Id;
    this.selectedmodelNbr = this.xoutresults[this.x].model_Nbr;
    // Populate form Data
    this.databaseService.getxLevel(id)
    .subscribe(xLevelresults => this.xLevelresults = xLevelresults);
    this.databaseService.getxmodel(id, this.selectedLevel)
    .subscribe(xmodelresults => this.xmodelresults = xmodelresults);
    this.databaseService.getxSig(id, this.selectedLevel, this.selectedDate)
    .subscribe(xsigresults => this.xsigresults = xsigresults);
    // Set Vals
    this.modelName = this.xoutresults[this.x].model_Name;
    this.TransactionDate = this.xoutresults[this.x].Calc_Dt;
    this.MakeName = this.xoutresults[this.x].Make_Level_Name;


    // Populate the outstanding x Requests effecting the current request
    this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
    .subscribe(curxpayresults => this.curxpayresults = curxpayresults,
      error => console.log('ERROR!'),
      () => {
      // Set the effect on Outs Prin
      if (this.curxpayresults.length === 0) {
        this.selectedEffect = 0;
      } else {
      this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
      }
      // Populate model Level Data
  this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
      .subscribe(xpayresults => this.xpayresults = xpayresults,
        error => console.log('ERROR!'),
        // Check that Max CMT can cover the request
        () => {    console.log(this.xpayresults[0].reaminder);
          if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
            // snack
            if (this.xpayresults[0].reaminder < 0) {
              this.snackBar.open('You:: ' +
               (this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
            } else {
              this.snackBar.open('You: ' +
               (this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
            }
            } else {
    // Populate Class and team Level Data for Screen
    this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
    .subscribe(
        (xpayclassresults) => {
            this.xpayclassresults = xpayclassresults;
            for (const xpayclassresult of this.xpayclassresults) {
                this.selectedClassId = xpayclassresult.Class_ID;
                console.log(this.selectedClassId);
                this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
                  , this.selectedAmount, this.selectedClassId, this.selectedEffect )
                    .subscribe((xpayteamresults) => {
                        this.xpayteamresults = xpayteamresults;
                        this.FinalArray.push(this.xpayteamresults);
                    }, error => console.log('ERROR!'),
                    () => {
                      this.DateDisabled = false;
                      this.SubmitDisabled = false;
                    });
            }
        });

    // Get team Level Data for SP submissions
    this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
      , this.selectedAmount)
    .subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
      error => console.log('ERROR!'),
       () => {
       });
            }
        });
      });
  }  if (this.nextswitch === true) {
    this.SubmitDisabled = true;
    this.DateDisabled = true;
    this.selectedAmount = event.target.value;
    this.xpayresults = [];
    this.xpayclassresults = [];
    this.xpayteamresults = [];
    this.xpayteamspresults = [];
    this.curxpayresults = [];
    this.FinalArray =  [];
    const id = this.route.snapshot.paramMap.get('id');

    // Populate the outstanding x Requests effecting the current request
    this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
    .subscribe(curxpayresults => this.curxpayresults = curxpayresults,
      error => console.log('ERROR!'),
      () => {
      // Set the effect on Outs Prin
      if (this.curxpayresults.length === 0) {
        this.selectedEffect = 0;
      } else {
      this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
      }
      // Populate model Level Data
  this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
      .subscribe(xpayresults => this.xpayresults = xpayresults,
        error => console.log('ERROR!'),
        // Check that Max CMT can cover the request
        () => {    console.log(this.xpayresults[0].reaminder);
          if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
            // snack
            if (this.xpayresults[0].reaminder < 0) {
              this.snackBar.open('You:: ' +
               (this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
            } else {
              this.snackBar.open('You: ' +
               (this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
            }
            } else {
    // Populate Class and team Level Data for Screen
    this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
    .subscribe(
        (xpayclassresults) => {
            this.xpayclassresults = xpayclassresults;
            for (const xpayclassresult of this.xpayclassresults) {
                this.selectedClassId = xpayclassresult.Class_ID;
                console.log(this.selectedClassId);
                this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
                  , this.selectedAmount, this.selectedClassId, this.selectedEffect )
                    .subscribe((xpayteamresults) => {
                        this.xpayteamresults = xpayteamresults;
                        this.FinalArray.push(this.xpayteamresults);
                    }, error => console.log('ERROR!'),
                    () => {
                      this.DateDisabled = false;
                      this.SubmitDisabled = false;
                    });
            }
        });

    // Get team Level Data for SP submissions
    this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
      , this.selectedAmount)
    .subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
      error => console.log('ERROR!'),
       () => {
       });
            }
        });
      });
  } else {
  this.xsigresults = [];
  this.selectedSigId = undefined;
  this.SubmitDisabled = true;
  this.DateDisabled = true;
  this.SigDisabled = false;
  this.xpayresults = [];
  this.xpayclassresults = [];
  this.xpayteamresults = [];
  this.xpayteamspresults = [];
  this.curxpayresults = [];
  this.FinalArray =  [];
  const id = this.route.snapshot.paramMap.get('id');
  // Populate Signatory Drop-Down
  this.databaseService.getxSig(id, this.selectedLevel, this.selectedDate)
    .subscribe(xsigresults => this.xsigresults = xsigresults);
  // change amount value
  this.selectedAmount = event.target.value;
  console.log(this.selectedAmount);
  }
    // Populate Values for Notice Days Drop-Down
    const id = this.route.snapshot.paramMap.get('id');
this.databaseService.getNotice(id)
.subscribe(noticeresults => this.noticeresults = noticeresults,
  error => console.log('ERROR!'),
   () => {
     if (this.selectedAmount > 0) {
      this.noticedays = this.noticeresults[0].Min_Repay_Notice_Days;
      console.log(this.noticedays);
     } else {
      this.noticedays = this.noticeresults[0].Min_Adv_Notice_Days;
     }
   });
}

// // changes the actual value of the variable for selectedSigId based on user selection
changedSig (xsigresult: xSigResult) {
  this.SubmitDisabled = true;
  this.DateDisabled = false;
  this.selectedDate = undefined;
  this.xpayresults = [];
  this.xpayclassresults = [];
  this.xpayteamresults = [];
  this.xpayteamspresults = [];
  this.curxpayresults = [];
  this.FinalArray =  [];
  this.selectedSigId = (xsigresult ? xsigresult.Signatory_ID : 1 );
  console.log(this.selectedSigId);
}

  // changes the actual value of the variable for selectedDate based on user selection of the date and pulls corresponding data
  changedDate (event: any) {
    // Disable to ensure user enters correct data
    this.DateDisabled = true;
    this.SubmitDisabled = true;
    // change date value
    this.selectedDate = event.target.value;
    console.log(this.selectedDate);
    this.xpayresults = [];
    this.xpayclassresults = [];
    this.xpayteamresults = [];
    this.xpayteamspresults = [];
    this.curxpayresults = [];
    this.FinalArray =  [];
    const id = this.route.snapshot.paramMap.get('id');
    // Populate the outstanding x Requests effecting the current request
    this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
  .subscribe(curxpayresults => this.curxpayresults = curxpayresults,
    error => console.log('ERROR!'),
    () => {
      // Set the effect on Outs Prin
      if (this.curxpayresults.length === 0) {
        this.selectedEffect = 0;
      } else {
      this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
      }
      // Populate model Level Data
  this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
  .subscribe(xpayresults => this.xpayresults = xpayresults,
    error => console.log('ERROR!'),
    // Check that Max CMT can cover the request
    () => {    console.log(this.xpayresults[0].reaminder);
      if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
        // snack
        if (this.xpayresults[0].reaminder < 0) {
          this.snackBar.open('You:: ' +
           (this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
        } else {
          this.snackBar.open('Yo: ' +
           (this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
        }
        } else {
// Populate Class and team Level Data for Screen
this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
.subscribe(
    (xpayclassresults) => {
        this.xpayclassresults = xpayclassresults;
        for (const xpayclassresult of this.xpayclassresults) {
            this.selectedClassId = xpayclassresult.Class_ID;
            console.log(this.selectedClassId);
            this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
              , this.selectedAmount, this.selectedClassId, this.selectedEffect )
                .subscribe((xpayteamresults) => {
                    this.xpayteamresults = xpayteamresults;
                    this.FinalArray.push(this.xpayteamresults);
                }, error => console.log('ERROR!'),
                () => {
                  this.DateDisabled = false;
                  this.SubmitDisabled = false;
                });
        }
    });

// Get team Level Data for SP submissions
this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
  , this.selectedAmount)
.subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
  error => console.log('ERROR!'),
   () => {
   });
        }
    });
  });
  }

submit() {
  this.DateDisabled = true;
  this.ISDisabled = true;
  this.modelDisabled = true;
  this.SubmitDisabled = true;
  this.AmountDisabled = true;
  this.SigDisabled = true;
  if (this.selectedAmount > 0) {
  for (const xpayteamspresult of this.xpayteamspresults) {
    this.Advteam_DRAW_REPAY = (xpayteamspresult.team_DRAW_REPAY * -1);
    this.xspcall = ('\'' + this.selectedDate + '\',' +
      xpayteamspresult.Make_Level_Debt_ID + ',' + xpayteamspresult.Make_Id +
       ',' + xpayteamspresult.Make_Level_Id + ',' + xpayteamspresult.Class_ID + ',' +
       xpayteamspresult.Debt_ID + ',' + xpayteamspresult.team_ID + ',' +
       xpayteamspresult.team_DRAW_REPAY + ',' + '0' + ',' + this.Advteam_DRAW_REPAY);
       this.databaseService.getxSP(this.xspcall).subscribe(x_sp_results => this.x_sp_results = x_sp_results);
    }
  } else {
    for (const xpayteamspresult of this.xpayteamspresults) {
      this.xspcall = ('\'' + this.selectedDate + '\',' +
        xpayteamspresult.Make_Level_Debt_ID + ',' + xpayteamspresult.Make_Id +
         ',' + xpayteamspresult.Make_Level_Id + ',' + xpayteamspresult.Class_ID + ',' +
         xpayteamspresult.Debt_ID + ',' + xpayteamspresult.team_ID + ',' +
         '0' + ',' + xpayteamspresult.team_DRAW_REPAY + ',' + xpayteamspresult.team_DRAW_REPAY);
         this.databaseService.getxSP(this.xspcall).subscribe(x_sp_results => this.x_sp_results = x_sp_results);
  }
  }
  const id = this.route.snapshot.paramMap.get('id');
  this.router.navigate(['/dashboard', id]);
}

submitEditDel (val) {
  this.dateselect = '';
  this.delete = 'To DELETE an existing entry mark this 0 and submit.';
  this.DateDisabled = true;
  this.ISDisabled = true;
  this.modelDisabled = true;
  this.SubmitDisabled = true;
  this.AmountDisabled = false;
  this.SigDisabled = true;
  this.x = val;
  this.editswitch = true;
  console.log(this.x);
  this.xpayresults = [];
  this.xpayclassresults = [];
  this.xpayteamresults = [];
  this.xpayteamspresults = [];
  this.curxpayresults = [];
  this.FinalArray =  [];
  const id = this.route.snapshot.paramMap.get('id');
  // change all values
  this.selectedDate = this.xoutresults[this.x].Calc_Dt;
  this.selectedAmount = this.xoutresults[this.x].Advance;
  this.selectedLevel = this.xoutresults[this.x].Make_Level_Id;
  this.selectedmodelNbr = this.xoutresults[this.x].model_Nbr;
  // Set Vals
  this.modelName = this.xoutresults[this.x].model_Name;
  this.TransactionDate = this.xoutresults[this.x].Calc_Dt;
  this.MakeName = this.xoutresults[this.x].Make_Level_Name;


      // Populate the outstanding x Requests effecting the current request
      this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
      .subscribe(curxpayresults => this.curxpayresults = curxpayresults,
        error => console.log('ERROR!'),
        () => {
      // Set the effect on Outs Prin
      if (this.curxpayresults.length === 0) {
        this.selectedEffect = 0;
      } else {
      this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
      }
      // Populate model Level Data
  this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
      .subscribe(xpayresults => this.xpayresults = xpayresults,
        error => console.log('ERROR!'),
        // Check that Max CMT can cover the request
        () => {    console.log(this.xpayresults[0].reaminder);
          if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
            // snack
            if (this.xpayresults[0].reaminder < 0) {
              this.snackBar.open('You:: ' +
               (this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
            } else {
              this.snackBar.open('You:y: ' +
               (this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
            }
            } else {
// Populate Class and team Level Data for Screen
this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
.subscribe(
    (xpayclassresults) => {
        this.xpayclassresults = xpayclassresults;
        for (const xpayclassresult of this.xpayclassresults) {
            this.selectedClassId = xpayclassresult.Class_ID;
            console.log(this.selectedClassId);
            this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
              , this.selectedAmount, this.selectedClassId, this.selectedEffect)
                .subscribe((xpayteamresults) => {
                    this.xpayteamresults = xpayteamresults;
                    this.FinalArray.push(this.xpayteamresults);
                }, error => console.log('ERROR!'),
                () => {
                  this.AmountDisabled = false;
                  this.SubmitDisabled = false;
                });
        }
    });
// Get team Level Data for SP submissions
this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
  , this.selectedAmount)
.subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
  error => console.log('ERROR!'),
   () => {
   });
  }
});
        });
}


openDialog(): void {
  const id = this.route.snapshot.paramMap.get('id');
  const dialogRef = this.dialogx.open(xDialogComponent, {
    width: '880px'    });
    dialogRef.componentInstance.id = id;
    dialogRef.componentInstance.Levelid = this.selectedLevel;
    dialogRef.componentInstance.modelnbr = this.selectedmodelNbr;
    dialogRef.componentInstance.selectedDate = this.selectedDate;

  dialogRef.afterClosed().subscribe(result => {
    console.log('The dialog was closed');
    console.log(dialogRef.componentInstance.closeMessage);
// Clear All Arrays
this.selectedAmount = undefined;
this.nextswitch = true;
this.DateDisabled = true;
this.ISDisabled = true;
this.modelDisabled = true;
this.SubmitDisabled = true;
this.AmountDisabled = false;
this.SigDisabled = true;
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray =  [];
const id = this.route.snapshot.paramMap.get('id');
this.selectedmodelNbr = 2;
// No need to change values as all will remain same except amount

  });
}


  ngOnInit() {
    this.MakeService.changeUrlid(this.route.snapshot.paramMap.get('id'));
  // returns the outstanding x Draw/Repay
   const id = this.route.snapshot.paramMap.get('id');
  this.databaseService.getxOut(id).subscribe(xoutresults => this.xoutresults = xoutresults);
  // get the Make Level data
  this.databaseService.getxLevel(id)
  .subscribe(xLevelresults => this.xLevelresults = xLevelresults);
  // Disable to ensure user enters correct data
  this.SubmitDisabled = true;
  this.DateDisabled = true;
  this.SigDisabled = true;
  // get data for the dynamically chose Make group
    this.databaseService.getGroup(id)
      .subscribe(MakeGroups => this.MakeGroups = MakeGroups);
    // get today's and tomorrows's date
    this.date = new Date();
    this.tomorrow = (Date.now() + 86400000 );
    // format tomorrow's date for the initial run (using tomorrow as this is in the Borrowing Base)
    const d = new Date(this.tomorrow);
    let ym = '' + (d.getMonth() + 1);
    let yd = '' + d.getDate();
    const yy = d.getFullYear();
      if (ym.length < 2) {
        ym = '0' + ym;
      }
      if (yd.length < 2) {
        yd = '0' + yd;
      }
      const yformat = [yy, ym, yd].join('-');
  }

}

test-dialog.component.ts

import { AppRoutingModule } from './../../app-routing.module';
import { Component, OnInit } from '@angular/core';
import {MatDialogModule} from '@angular/material/dialog';
import {MatDialogRef, MAT_DIALOG_DATA, MatDialog} from '@angular/material/dialog';
import { Inject } from '@angular/core';
import { Observable } from 'rxjs';
import { databaseService, NextxResult } from '../database.service';
import { TrackerResult } from '../database.service';
import { HttpClient } from '@angular/common/http';
import { element } from 'protractor';
import { ActivatedRoute, Router, RouterLink, Routes  } from '@angular/router';


@Component({
  selector: 'app-x-dialog',
  templateUrl: './x-dialog.component.html',
  styleUrls: ['../style.css']
})
export class xDialogComponent implements OnInit {

  id: string;

  nextxresults: Array<NextxResult>;
  closeMessage: string;

  constructor(
    private databaseService: databaseService,
    private route: ActivatedRoute,
    private router: Router,
    public dialogRef: MatDialogRef<xDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

    onClose(): void {
      // set the closeMessage property here
    this.closeMessage = 'Pizza!';
    this.dialogRef.close(5);
    }
    screenClick(val) {
console.log(val);
    }

  ngOnInit() {

  this.databaseService.getNextx(this.id)
  .subscribe(nextxresults => this.nextxresults = nextxresults);
  }

}

The console.log comes back as undefined, any idea why I am not getting "Pizza!"?

Updated with all the code for both files to hopefully add more insight into my issue. Really appreciate any help to get this sorted out!

user68288
  • 702
  • 2
  • 6
  • 27
  • You can always set a property on the dialogue and read it in your `.afterClosed()` callback if you need to pass data – mhodges Jun 04 '18 at 16:42
  • I am very new to coding in general -- do you mind linking an example? I am not sure how to do that. – user68288 Jun 04 '18 at 16:43
  • In your `onClose()` function, you can set `this.dialogRef.closeMessage = "Pizza!"` and then in the `afterClose()` you can say `console.log(this.dialogRef.closeMessage)`. If TypeScript barks at you, you can extend the dialogue interface definition to add whatever property you want to set. – mhodges Jun 04 '18 at 16:45
  • When I try to add this.dialogRef.closeMessage to the onClose function I get the following error: Property 'closeMessage' does not exist on type 'MatDialogRef'. Thanks for helping by the way. – user68288 Jun 04 '18 at 16:50
  • That's what I meant by "If TypeScript barks at you...", anyway.. I just looked through some of my code using the same dialogues and it passes through the arguments into the `afterClosed()` callback. I'm not actually sure what the issue is now – mhodges Jun 04 '18 at 16:51
  • I have `this.dialogRef.close("yes");` and then in my component I say `this.dialogRef.afterClosed().subscribe(result => { if (result === "yes") { ... } });` and it works just fine. What version of @angular and @angular/material are you using? – mhodges Jun 04 '18 at 16:53
  • Could it be because my dialog has its own component versus having it contained in the same? – user68288 Jun 04 '18 at 16:55
  • Nope, that's exactly how I have it, too. What version of @angular and @angular/material are you using? – mhodges Jun 04 '18 at 16:55
  • My angular and angular/material are both latest versions. – user68288 Jun 04 '18 at 16:56
  • From the [Angular Material 6.2.0 Docs](https://material.angular.io/components/dialog/overview): "Components created via MatDialog can inject MatDialogRef and use it to close the dialog in which they are contained. When closing, an optional result value can be provided. This result value is forwarded as the result of the afterClosed promise." This should be working. Can you post your entire test-dialog.component.ts file? – mhodges Jun 04 '18 at 17:17
  • I updated my OP to include the entirety of the code. – user68288 Jun 04 '18 at 17:28
  • Hmm, I don't know what to tell you.Everything looks right. Can you try stripping away code (by commenting it out) until you have the least code possible to reproduce this? Something else may be conflicting. – mhodges Jun 04 '18 at 17:42
  • @mhodges I stripped away everything that would not cause errors and it still will not work. Thanks for the help but I am unsure how to move forward. – user68288 Jun 04 '18 at 18:09
  • This is really strange `:\ ` For the time being, I guess you can use the workaround I mentioned before by adding `closeMessage` as a property on your dialog component. Then set `this.closeMessage = "Pizza!";` in your dialog component `onClose()` function, and then log out `dialogRef.componentInstance.closeMessage` in your `afterClosed()` callback. – mhodges Jun 04 '18 at 18:13
  • Sorry -- I am still unsure how to do that. Where do I add the property? – user68288 Jun 04 '18 at 18:23
  • I'll write up an answer. Don't upvote or accept it, I just want to show you the code – mhodges Jun 04 '18 at 18:25

2 Answers2

6

This is a possible workaround, but not the correct solution. Your code should be working as-is (according to the documentation) so there is something else going on that is causing it to break. Without a lot more context into your code, it will be hard to determine exactly what the issue is. For now, you can try this:

test-dialog.component.ts

export class TestDialogComponent implements OnInit {

  id: string;
  nextresults: Array<NextResult>;
  closeMessage: string = "";      

  constructor(
    ...
    public dialogRef: MatDialogRef<TestDialogComponent>, 
    ...) { }

  onClose(): void {
    // set the closeMessage property here
    this.closeMessage = "Pizza!";
    this.dialogRef.close('ref');
  }
  ...
}

test.component.ts

openDialog() {
  const id = this.route.snapshot.paramMap.get('id');
  const dialogRef = this.dialog.open(TestDialogComponent, {
    width: '880px'    });
    dialogRef.componentInstance.id = id;

  dialogRef.afterClosed().subscribe(result => {
    console.log('The dialog was closed');
    // reference the closeMessage property here
    console.log(dialogRef.componentInstance.closeMessage);
  });
}
mhodges
  • 10,938
  • 2
  • 28
  • 46
  • I feel terrible none of this is working. I did exactly what is above and I am receiving no errors or underlines but somehow it still displays as "undefined" in my console... – user68288 Jun 04 '18 at 18:32
  • @user68288 Well, that is a telltale sign that your dialog reference is getting overwritten/changed/lost. Can you post your entire `test.component.ts` in your original question? – mhodges Jun 04 '18 at 18:34
  • Unfortunately the code contains a lot of personal info and is over 600 lines long so it would take a lot of cleaning before I could post it online. Is there anything in particular I should look out for that maybe I could find? – user68288 Jun 04 '18 at 18:41
  • @user68288 Part of a good, answerable question on SO is to create a [Minimal, Complete, Verifiable Example (MCVE)](https://stackoverflow.com/help/mcve). It should take no more than 10-15 minutes to strip it down. – mhodges Jun 04 '18 at 18:51
  • @user68288 This may be a dumb question, but are you sure you are rebuilding your app after you make changes? I've done that before. – mhodges Jun 04 '18 at 18:53
  • Definitely rebuilding :) I will strip down my code now. Thanks. – user68288 Jun 04 '18 at 18:57
  • I added all the detail, hopefully it helps. @mhodges – user68288 Jun 04 '18 at 19:05
  • @user68288 Thank you. Can you post what your `xDialogComponent` looks like now? Just to make sure that everything looks good in the actual component you are using. Your test-dialog.component.ts looks fine, but maybe there is a discrepancy in your actual dialog component file – mhodges Jun 04 '18 at 20:24
  • Updated that in the OP as well. Also just as a note I am on material/cdk 6.0.2 – user68288 Jun 04 '18 at 20:28
2
  1. Component A calls the dialog open event
  2. User type some values in the dialog component (Component B) and click on Save
  3. Component B calls the this.dialogRef.close(this.worksheetName.value) with the desired return values
  4. this.dialogRef.afterClosed().subscribe getting invoked with the value passed

Component A

addWorksheet(): void {
    this.dialogRef = this.dialog.open(CreateWorksheetComponent, { width: '400px' });
    this.afterClosed();
  }
  private afterClosed(): void {
    this.dialogRef.afterClosed().subscribe((worksheetName: string) => {
      console.log(worksheetName)
      this.createWorksheet(worksheetName);
    });
  }

Component B

createWorksheet(): void {
    if (this.worksheetName.valid) {
      this.dialogRef.close(this.worksheetName.value);
    }
  }

  errorMessage(): void {
    return Config.ErrorMessages.InvalidWorksheetName;
  }

  cancel(): void {
    this.dialogRef.close();
  }

Component B HTML

<div>
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Ansichtiname" [formControl]="worksheetName">
    <mat-error *ngIf="worksheetName?.invalid">{{errorMessage()}}</mat-error>
  </mat-form-field>
</div>
<mat-card-actions>
  <button mat-button (click)="cancel()">Abbrechen</button>
  <button mat-button (click)="createWorksheet()" [disabled]="worksheetName?.invalid">Speichern</button>
</mat-card-actions>
Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140