在 slide-toggle 组件中添加一个 confirm 弹窗,当用户改变开关状态时弹出,等待用户确认后再更新数据。可以通过以下代码实现:
HTML:
Slide Toggle
TypeScript:
import { MatDialog } from '@angular/material/dialog';
import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';
export class MyComponent {
isChecked = false;
constructor(public dialog: MatDialog) {}
confirmToggle(event: MatSlideToggleChange): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
data: { isChecked: event.checked }
});
dialogRef.afterClosed().subscribe(result => {
if (result === 'confirm') {
// 用户点击确认,更新数据
this.isChecked = event.checked;
} else {
// 用户取消操作,还原开关状态
this.isChecked = !event.checked;
}
});
}
}
在 confirm-dialog.component.ts 中实现 ConfirmDialogComponent 组件,该组件可以通过 MatDialog 打开对话框,允许用户确认或取消操作。
HTML:
Confirm
Are you sure you want to toggle the switch?
TypeScript:
import { Component } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-confirm-dialog',
templateUrl: './confirm-dialog.component.html'
})
export class ConfirmDialogComponent {
constructor(
public dialogRef: MatDialogRef,
@Inject(MAT_DIALOG_DATA) public data: { isChecked: boolean }
) {}
onCancelClick(): void {
this.dialogRef.close();
}
}