sky*_*dev 6 angular-material angular
我试图添加一个在我的Web服务执行之前被调用的Angular Material对话框(仅标题和yes / no)。事实是,我不想在单独的组件中创建对话框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>
Run Code Online (Sandbox Code Playgroud)
callAPI() {
this.http.get<any>('https://example.com/api').subscribe(data => {
this.data = data;
this.loading = false;
},
err => {
this.loading = false;
});
}
Run Code Online (Sandbox Code Playgroud)
Edr*_*ric 13
更新:我假设TemplateRef的类型参数是组件引用是不正确的- 事实上,它实际上是“嵌入视图的数据绑定上下文”,如该TemplateRef#createEmbeddedView方法的文档中所示:
Run Code Online (Sandbox Code Playgroud)abstract createEmbeddedView(context: C): EmbeddedViewRef<C>描述:
基于此模板实例化嵌入视图,并将其附加到视图容器。
参数:
context(typeC:) 嵌入视图的数据绑定上下文,在用法中声明。
您可以将模板引用传递给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>
Run Code Online (Sandbox Code Playgroud)
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.');
}
}
})
}
Run Code Online (Sandbox Code Playgroud)