角材料创建对话框与现有功能位于同一组件中

时间:2018-09-13 09:54:40

标签: angular angular-material

我正在尝试添加一个Angular Material对话框(仅标题和yes / no),该对话框在我的Web服务执行之前被调用。事实是,我不想在单独的组件中创建对话框HTML。我需要对话框HTML与现有代码位于同一文件中。当我单击callAPI按钮时,该对话框需要打开。 这是我现有的组件代码

<mat-tab-group>
    <mat-tab label="Tab 1">
       <button mat-flat-button color="warn" (click)="callAPI()">Open Dialog</button>
    </mat-tab>
    <mat-tab label="Tab 2">
    </mat-tab>
</mat-tab-group>
callAPI() {
    this.http.get<any>('https://example.com/api').subscribe(data => {
      this.data = data;
      this.loading = false;
    },
    err => {
        this.loading = false;
    });
}

2 个答案:

答案 0 :(得分:3)

您可以将template reference传递到MatDialog#open

<ng-template #callAPIDialog>
    <h2 matDialogTitle>Hello dialog!</h2>
    <mat-dialog-actions align="end">
        <button mat-button matDialogClose="no">No</button>
        <button mat-button matDialogClose="yes">Yes</button>
    </mat-dialog-actions>
</ng-template>
import { TemplateRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material';

@Component({ /* */ })
export class MyComponent {

    @ViewChild('callAPIDialog') callAPIDialog: TemplateRef;

    constructor(private dialog: MatDialog) { }

    callAPI() {
        let dialogRef = this.dialog.open(this.callAPIDialog);
        dialogRef.afterClosed().subscribe(result => {
            // Note: If the user clicks outside the dialog or presses the escape key, there'll be no result
            if (result !== undefined) {
                if (result === 'yes') {
                    // TODO: Replace the following line with your code.
                    console.log('User clicked yes.');
                } else if (result === 'no') {
                    // TODO: Replace the following line with your code.
                    console.log('User clicked no.');
                }
            }
        })
    }

答案 1 :(得分:1)

最初,我尝试了Edric的建议,并且对话框完美打开,但是当我想在经过一些处理之后而不是仅使用模板指令matDialogClose从组件中关闭对话框时,我有点迷失。因此,我对此主题进行了搜索,花了我一段时间才把所有的部分都连接起来,发现模板引用与该模板的对话框引用有些不同。因此,动手将所有内容放在一起...

<!-- Edit Company -->
<ng-template #editCompanyModal>
  <div class="mat-dialog-header border-bottom">
    <h2 mat-dialog-title class="mb-0">Edit Company</h2>
    <div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="12px">
      <button mat-icon-button matDialogClose tabindex="-1">
        <mat-icon aria-label="Close dialog">close</mat-icon>
      </button>
    </div>
  </div>
  <form #editCompanyForm="ngForm" role="form" novalidate name="editCompanyForm"
          (submit)="editCompanyFormSubmit(editCompanyForm, $event)">
    <mat-dialog-content>
      <fieldset>
        ...
      </fieldset>
    </mat-dialog-content>
    <mat-dialog-actions class="border-top">
      <button type="button" mat-button matDialogClose>Cancel</button>
      <button type="submit" mat-raised-button color="accent"
              [disabled]="!editCompanyForm.valid">Save changes</button>
    </mat-dialog-actions>
  </form>
</ng-template>
@Component({
  ...
})
export class AccountCompanyComponent {

  @ViewChild('editCompanyModal') editCompanyModal: TemplateRef<any>;
  private editCompanyDialogRef: MatDialogRef<TemplateRef<any>>;

  constructor(public dialog: MatDialog) {}

  // Dialog handling

  openCompanyDetailsDialog(): void {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.restoreFocus = false;
    dialogConfig.autoFocus = false;
    dialogConfig.role = 'dialog';

    this.editCompanyDialogRef = this.dialog.open(this.editCompanyModal, dialogConfig);

    this.editCompanyDialogRef.afterClosed().subscribe(result => {
      consoleOut('The dialog was closed...');
    });
  }

  closeCompanyDetailsDialog() {
    this.editCompanyDialogRef.close();
  }

  editCompanyFormSubmit(form: NgForm, event: any) {
    event.preventDefault();
    if (!form.valid) {
      return false;
    }
    this.saveCompanyData();
  }

  saveCompanyData() {
    this.companiesService.updateCompanyDetails(this.companyDetailsModel).subscribe(response => {
      if ( response ) {
        // close dialog
        self.closeCompanyDetailsDialog();
        // Notify success
        this.uiHelpers.showAlert('The Company details have been updated!', null, AlertType.Success);
      } else {
        this.uiHelpers.showAlert('Oops!', 'There was a problem updating the Company details', AlertType.Error);
      }
    });
  }

}