通知后关闭Md对话框

时间:2018-05-31 12:31:25

标签: html angular typescript mddialog angular2-toaster

我有一个用户可以输入数据的对话框,点击"创建"后,我的对话框关闭,用户收到通知。我想在用户收到通知后关闭我的对话框,如果用户输入了错误的数据,用户也应该收到通知,对话框也不应该关闭。

目前,一切正常但我希望我的对话框在通知(toster服务)后会消失。

任何人都可以帮我解决这个问题,以便我的对话框会一直存在,直到我收到成功通知和错误通知吗?

exhibit.component.ts(主要组成部分)

  createExhibit(event: any) {
    let context = this;
    this.createDialogRef = this.dialog.open(CreateExhibitDialogComponent, { width: '45em', data: {} });
    this.createDialogRef.afterClosed().subscribe(
      (newExhibit: Exhibit) => {
        if (newExhibit.latitude) { newExhibit.latitude = newExhibit.latitude.toString().replace(/,/g, '.'); }
        if (newExhibit.longitude) { newExhibit.longitude = newExhibit.longitude.toString().replace(/,/g, '.'); }
        if (newExhibit) {
          this.exhibitService.createExhibit(newExhibit)
            .then(
              () => {
                this.toasterService.pop('success', this.translate('exhibit saved'));
                setTimeout(function () {
                  context.reloadList();
                }, 1000);
              }
            ).catch(
              error => this.toasterService.pop('error', this.translate('Error while saving'), error)
            );
        }
        this.createDialogRef = null;
      }
    );
  }

createExhibit.component.ts

<h1 md-dialog-title>{{ 'create exhibit' | translate }}</h1>

<md-dialog-content>
  <form id="new-exhibit-form">
    <md-input-container>
      <input mdInput placeholder="{{ 'name' | translate }}" [(ngModel)]="exhibit.name" name="name" required>
    </md-input-container>
    <md-input-container>
       <textarea
         mdInput
         mdTextareaAutosize
         #autosize="mdTextareaAutosize"
         placeholder="{{ 'description' | translate }}"
         [(ngModel)]="exhibit.description"
         name="desc"></textarea>
    </md-input-container>

    <div layout="row" layout-align="start center" flex>
      <md-icon _ngcontent-c7="" class="mat-icon material-icons centered" role="img" aria-hidden="true">search</md-icon>
      <md-input-container>
        <input mdInput  placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
      </md-input-container>
      <md-input-container>
        <input (blur)="updateMap()" mdInput type="number" min="-90" max="90" step="0.000001"
               placeholder="{{ 'latitude' | translate }}" [(ngModel)]="exhibit.latitude" name="lat">
      </md-input-container>
      <md-input-container>
        <input (blur)="updateMap()" mdInput type="number" min="-180" max="180" step="0.000001"
               placeholder="{{ 'longitude' | translate }}" [(ngModel)]="exhibit.longitude" name="long">
      </md-input-container>
      <md-select  class="align-right" placeholder="{{ 'status' | translate }}" [(ngModel)]="exhibit.status" name="status">
        <md-option *ngFor="let statusOption of statusOptions" [value]="statusOption">{{ statusOption | translate }}</md-option>
      </md-select>
    </div>
    <agm-map (mapClick)="selectLocation($event)" [zoom]=15 [latitude]="lat" [longitude]="lng">
      <agm-marker [iconUrl]="'../../../images/map-marker.png'" *ngIf="exhibit.longitude && exhibit.latitude" [latitude]="exhibit.latitude" [longitude]="exhibit.longitude"></agm-marker>
    </agm-map>
  </form>
</md-dialog-content>

<md-dialog-actions align="end">
  <button md-dialog-close md-raised-button>
    {{ 'cancel' | translate }}
    <md-icon>cancel</md-icon>
  </button>
  <button md-raised-button [disabled]="!exhibit.isValid()" color="primary" (click)="dialogRef.close(exhibit)">
    {{ 'create' | translate }}
    <md-icon>add_circle</md-icon>
  </button>
</md-dialog-actions>

怎么做?

1 个答案:

答案 0 :(得分:1)

windmaomao所述,您需要手动调用dialog close()方法。材质对话框组件只能从afterClose()或beforeClose()中观察到,并且这些方法侦听通过close()方法传递的数据。 close()方法关闭课程对话框,这不是我们的期望。您需要使用一种Observable或EventEmitter来实现组件和对话框之间的通信系统。 我已经为您的问题准备了简化的解决方案。诀窍是,您可以使用“ componentInstance” getter获取对对话框组件的任何字段或方法的引用。

对话框组件

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

  @Component({
    selector: 'app-simple-dialog',
    template: `<h2 mat-dialog-title>Entering some data</h2>
    <mat-dialog-content>Is data OK?</mat-dialog-content>
    <mat-dialog-actions>
      <button mat-button (click)="actionNo()">No</button>
      <button mat-button (click)="actionYes()">Yes</button>
    </mat-dialog-actions>`,
    styleUrls: ['./simple-dialog.component.css']
  })
  export class SimpleDialogComponent implements OnInit {

    private _action: EventEmitter<boolean> = new EventEmitter<boolean>();
    answer = this._action.asObservable();

    constructor(public dialogRef: MatDialogRef<SimpleDialogComponent>) { }

    actionYes() {
      this._action.next(true);
    }

    actionNo() {
      this._action.next(false);
    }

    closeDialog() {
      this.dialogRef.close();
    }

    ngOnInit() {
    }

  }

要包含在您的主要组件中的HTML模板摘录代码:

    <button (click)="openDialog()">Open Dialog</button>

openDialog()方法的代码:

openDialog() {
  let dialogRef = this.dialog.open(SimpleDialogComponent);
  dialogRef.componentInstance.answer.subscribe( answer => {
    console.log('Answer from Dialog: ' + answer);
    switch(answer) {
      case true:
        console.log('Data is OK. Closing dialog');
        //do some complicated stuff
        dialogRef.componentInstance.closeDialog();
        //can be simple: dialogRef.close(); 
        break;
      case false:
        console.log('Data is not OK. Not closing dialog. Show some toaster');
        break;
    }
    }
  )
}