首页 > 解决方案 > 带有事件的通用组件

问题描述

我是 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);
  }

}

推荐阅读