首页 > 解决方案 > 在与现有功能相同的组件中创建角材料对话框

问题描述

我正在尝试添加一个在我的 Web 服务执行之前调用的 Angular Material 对话框(只是一个标题和是/否)。问题是我不想在单独的组件中创建对话框 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;
    });
}

标签: angularangular-material

解决方案


更新:我认为TemplateRef's 类型参数是组件引用的假设是不正确的 - 事实上,它实际上是“嵌入式视图的数据绑定上下文”,如该TemplateRef#createEmbeddedView方法的文档中所示:

abstract createEmbeddedView(context: C): EmbeddedViewRef<C>

描述:

基于此模板实例化嵌入视图,并将其附加到视图容器。

参数:

context(type: C) 嵌入视图的数据绑定上下文,在用法中声明。


您可以将模板引用传递给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<any>;

    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.');
                }
            }
        })
    }

推荐阅读