You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何首次调用Confirm Service时修改MatDialog按钮文本?

解决方案

1. 扩展ConfirmData接口,支持自定义按钮文本

在confirm.service.ts中为接口新增两个可选字段,用于接收自定义按钮文本:

interface ConfirmData {
  title?: string;
  message?: string;
  confirmText?: string; // 对应原YES按钮
  cancelText?: string;  // 对应原NO按钮
}

2. 在确认服务中设置按钮文本默认值

修改confirm方法,给按钮文本添加默认值,未传入自定义文本时自动使用YES/NO:

@Injectable()
export class AppConfirmService {
  constructor(private dialog: MatDialog) { }
  public confirm(data: ConfirmData = {}): Observable<boolean> {
    // 整合传入数据与默认值
    const dialogData = {
      title: data.title || '',
      message: data.message || '',
      confirmText: data.confirmText || 'YES',
      cancelText: data.cancelText || 'NO'
    };
    const dialogRef: MatDialogRef<AppConfirmComponent> = this.dialog.open(AppConfirmComponent, {
      width: '380px',
      disableClose: true,
      data: dialogData
    });
    return dialogRef.afterClosed();
  }
}

3. 修改确认组件模板,动态绑定按钮文本

在confirm.component.html中,将硬编码的按钮文本替换为从data中读取的动态值:

<h1 matDialogTitle class="mb-05">{{ data.title }}</h1>
<div mat-dialog-content class="mb-1">{{ data.message }}</div>
<div mat-dialog-actions>
    <button type="button" mat-raised-button color="primary" (click)="dialogRef.close(true)">{{ data.confirmText }}</button>
    &nbsp;
    <span fxFlex></span>
    <button type="button" color="secondary" mat-raised-button (click)="dialogRef.close(false)">{{ data.cancelText }}</button>
</div>
<div>&nbsp;</div>

4. 在调用组件中首次传入自定义按钮文本

在search.component.ts的deleteDistribution方法里,首次调用服务时传入自定义按钮文本,后续调用则使用默认值:

deleteDistribution(row) {
  // 首次调用:传入自定义按钮文本
  this.confirmService.confirm({
    message: 'Do you want to delete all or delete single one?',
    confirmText: 'Delete All',
    cancelText: 'Delete One'
  }).subscribe((res) => {
    if (res) {
      // 后续调用:自动使用默认的YES/NO按钮文本
      this.confirmService
          .confirm({message: `Are you sure you want to delete all?`})
          .subscribe((res) => {
             if (res) {
              // do something
             }
          });
    } else {
      // choose to delete one, go somewhere else
    }
  });
}

这种方案无需复制服务,通过扩展原有数据结构实现了动态按钮文本的需求,同时保留了原有默认行为,完全满足你的要求。

内容的提问来源于stack exchange,提问作者Thomaz1593

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:40:40