angular - 在与现有功能相同的组件中创建角材料对话框
问题描述
我正在尝试添加一个在我的 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;
});
}
解决方案
更新:我认为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.');
}
}
})
}
推荐阅读
- angular - Angular:ngif动画跳跃!从 DOM 中删除前一个元素后如何为 ngif 元素设置动画?
- javascript - 使用自定义函数对数组进行排序
- r - 如何将`c(a,b)`转换为`table(a,b)`的参数?
- android - onLaunch 循环运行
- scala - 如何从 CSV 批量发送数据到 Kafka 生产者
- xamarin.forms - Xamarin.Forms 多个 WebViews 但 OnPageFinished 似乎只适用于最后一个 Webview?
- javascript - 反应错误无效钩子和状态未定义
- excel - 在特定人名文件夹中保存多个 PDF 字母
- vuex - 在不使用 fetch 的情况下更新服务器端的 Nuxt 存储(已弃用)
- libgit2 - libgit2中的全局操作需要同步吗?