Skip to content Skip to sidebar Skip to footer

How To Pass Data To Afterclosed() In Angular Material Dialog In Angular 6

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 test-dialog.component.ts Th

Solution 1:

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

exportclassTestDialogComponentimplementsOnInit {

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

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

  onClose(): void {
    // set the closeMessage property herethis.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 hereconsole.log(dialogRef.componentInstance.closeMessage);
  });
}

Solution 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-fieldclass="example-full-width"><inputmatInputplaceholder="Ansichtiname" [formControl]="worksheetName"><mat-error *ngIf="worksheetName?.invalid">{{errorMessage()}}</mat-error></mat-form-field></div><mat-card-actions><buttonmat-button (click)="cancel()">Abbrechen</button><buttonmat-button (click)="createWorksheet()" [disabled]="worksheetName?.invalid">Speichern</button></mat-card-actions>

Post a Comment for "How To Pass Data To Afterclosed() In Angular Material Dialog In Angular 6"