angular - Angular 材料:是否可以使用 ng-template 创建模态(或对话框)?
问题描述
在我的项目中,我使用了 ngx-bootstrap 的对话框组件,它接受您ng-template
并将其显示为您的模式。
ng-template
由于许多原因,使用是有利的,最重要的是,如果ng-template
存在于同一个组件中,则没有通信障碍(模态组件和原始组件之间)。这样我就可以毫无问题地调用我的组件方法。例如,在下面的代码selectNextRow()
中将更改我表中的行,因此selectedRow_Session
下一行的数据将显示在模态中。
app.component.ts
/** display selectedRow_Session on modal */
<ng-template #sessionDetailTemplate>
<app-session-detail-model
[session]="selectedRow_Session"
[bot]="bot"
(selectNextRow)="selectNextRow()"
(closeModel$)="modalRef.hide()"
(selectPrevRow)="selectPrevRow()"
[pageNumberOfCurrentRowSelected]="pageNumberOfCurrentRowSelected"
[indexOfCurrentRowSelected]="indexOfCurrentRowSelected"
[finalDfState]="selectedRow_Session.df_state"
[sessionDataStore]="selectedRow_Session.data_store">
</app-session-detail-model>
</ng-template>
在 Angular Material Dialogs 中,我只能找到可以使用 onlyComponent
而不是创建模态的 API ng-template
。
有没有办法使用Angular Material来做到这一点,无论有没有对话框?
解决方案
如评论中所述,您可以将 TemplateRef 与 @angular/material MatDialog 一起使用。您可以在此处找到 API 参考:Angular Material MatDialog。
这是一个显示如何执行此操作的最小示例:
import { Component, ViewChild, TemplateRef } from '@angular/core';
import { MatDialog } from '@angular/material';
@Component({
selector: 'dialog-overview-example',
template: `
<div [style.margin.px]="10">
<button mat-raised-button (click)="openDialog()">Open Modal via Component Controller</button>
</div>
<div [style.margin.px]="10">
<button mat-raised-button (click)="dialog.open(myTemplate)">Open Modal directly in template</button>
</div>
<ng-template #myTemplate>
<div>
<h1>This is a template</h1>
</div>
</ng-template>
`
})
export class DialogOverviewExample {
@ViewChild('myTemplate') customTemplate: TemplateRef<any>;
constructor(public dialog: MatDialog) {}
openDialog(): void {
const dialogRef = this.dialog.open(this.customTemplate, {
width: '250px'
});
dialogRef.afterClosed().subscribe(() => {
console.log('The dialog was closed');
});
}
}
这是一个使用 Angular v6 的实时示例:Stackblitz Live Example。
希望能帮助到你!
推荐阅读
- reactjs - 如何让 Toast 出现?
- github - Github Actions 子目录作为 NPM 模块
- mysql - 插入带有 3 个表的查询
- javascript - 使用 JS/html 控制/延迟 Shiny DT 数据表的搜索速度
- sql-server - SQL Server - 不支持的密钥库提供程序 MSSQL_JAVA_KEYSTORE
- r - R:将行值复制到 dplyr/tidyr 中的新行
- amazon-web-services - Terraform:在另一个资源中引用在 for_each 中创建的资源
- java - 从 POST 获取 415 错误以下载文件
- notifications - neomutt 中电子邮件发件人的状态格式
- amazon-web-services - AWS CloudFormation:无法为 URL 到 URL 映射创建 Route53 记录资源