我对angular还是比较陌生,我对创建一个可以在多种情况下使用的通用确认弹出窗口组件感兴趣。例如,对于删除或保存条目,用户必须确认操作,因此将显示一个简单的弹出窗口(一些文本,“取消”和“确定”按钮)。根据用户执行的操作,我希望该“确定”按钮删除或保存项目。这可以实现吗? (将需要执行的相应方法发送到该通用组件)。
答案 0 :(得分:0)
当然可以。只需为您的弹出窗口提供一个异步API。为了查看它,构建器模式可能很有用。确保返回Promise / Observable,以便在打开对话框的组件中可以根据结果做出反应。
我必须对此答案进行简化的一些代码。它使用物料对话框创建具有取消,标题,消息和确认的通用确认对话框。订阅show
以获得结果。您将不得不使用此代码,它没有以这种简单的形式进行过测试。但这应该可以让您了解如何完成通用对话框。
(例如从您的组件中)调用它:
new ConfirmDialogPresenter(this.mdDialog);
confirm-dialog-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();
}
}
confirm-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>
confirm-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);
}
}