angular - 带有事件的通用组件
问题描述
我是 Angular 的新手,我有兴趣创建一个可用于多种场景的通用确认弹出组件。例如,对于删除或保存条目,用户必须确认操作,因此将显示一个简单的弹出窗口(一些文本、一个取消和确定按钮)。根据用户执行的操作,我希望该确定按钮删除或保存项目。这可以实现吗?如何实现?(将需要执行的相应方法发送到该通用组件)。
解决方案
当然有可能。只需为您的弹出窗口提供一个异步 API。为了查看它,构建器模式可能很有用。确保返回 Promise/Observable,以便在打开对话框的组件中,您可以根据结果做出反应。
我必须为这个答案简化一些代码。它使用材料对话框来创建一个带有取消、标题、消息和确认的通用确认对话框。订阅以show
获得结果。您将不得不使用此代码,它没有以这种更简单的形式进行测试。但它应该让您了解如何完成通用对话框。
用(例如从您的组件)调用它:
new ConfirmDialogPresenter(this.mdDialog);
确认对话框instance.ts
export class ConfirmDialogPresenter {
private _title = '';
private _message = '';
private _confirmLabel = '';
private _cancelLabel = '';
constructor(private mdDialog: MatDialog) {
}
title(title: string): ConfirmDialogPresenter {
this._title = title;
return this;
}
message(message: string): ConfirmDialogPresenter {
this._message = message;
return this;
}
confirmLabel(confirmLabel: string): ConfirmDialogPresenter {
this._confirmLabel = confirmLabel;
return this;
}
cancelLabel(cancelLabel: string): ConfirmDialogPresenter {
this._cancelLabel = cancelLabel;
return this;
}
show(): Observable<boolean | undefined> {
const dialogRef = this.mdDialog.open(ConfirmDialogComponent);
dialogRef.componentInstance.title = this._title;
dialogRef.componentInstance.message = this._message;
dialogRef.componentInstance.confirmLabel = this._confirmLabel;
dialogRef.componentInstance.cancelLabel = this._cancelLabel;
return dialogRef.afterClosed();
}
}
确认-dialog.component.html
<h1 mat-dialog-title>
{{title}}
</h1>
<mat-dialog-content>
{{message}}
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button mat-raised-button color="accent" (click)="confirm()">{{confirmLabel}}</button>
<button mat-button mat-raised-button color="secondary" (click)="close()">{{cancelLabel}}</button>
</mat-dialog-actions>
确认-dialog.component.ts
@Component({
selector: 'app-confirm-dialog',
templateUrl: './confirm-dialog.component.html',
styleUrls: ['./confirm-dialog.component.scss']
})
export class ConfirmDialogComponent implements OnInit {
title: string;
message: string;
confirmLabel: string = "Okay!";
cancelLabel: string = "Cancel";
constructor(public readonly dialogRef: MatDialogRef<ConfirmDialogComponent>) {
}
ngOnInit() {
}
close() {
this.dialogRef.close(false);
}
confirm() {
this.dialogRef.close(true);
}
}
推荐阅读
- elasticsearch - 查询 ElasticSearch - 在不同时间匹配的多个术语
- node.js - Mongoose 独特的字段处理
- sockets - 为什么 Haskell 中的 System.Timeout 不适用于套接字?
- r - 如何在多个 blogdown 帖子中加载相同的所需包?
- java - Android Intent Service APP在后台静默工作仍以白屏启动
- c# - Startup.cs 中 SPA 源路径的 GetCurrentDirectory() 正在为 VS2017 和 VS Code 返回不同的路径
- android - 在片段上的 getCurrentUser().getUid() 上获取空对象引用
- sql - 分组数据问题
- c# - 如何解决 EPPlus 读取大 Excel 文件的问题
- docker - 由 root 而不是 laradock 用户创建的新的每日日志文件