منع المستخدمين من مغادرة الصفحة في Angular
(Prevent Users from Leaving a Page in Angular)
يمكنك منع المستخدمين من مغادرة الصفحة من خلال المتصفح بالكريقة أدناه:
ngOnInit() {
window.addEventListener('beforeunload', (event) => {
event.preventDefault(); // Prevent default behavior
const confirmationMessage = 'Leaving this page will discard any unsaved changes. Are you sure you want to leave?';
event.returnValue = confirmationMessage; // Set custom message
});
}
أما من خلال أحداث الصفحة فيكون بهذه الطريقة (الضغط على زر داخلي):
@ViewChild('leaveDialog', { static: true }) leaveDialog: TemplateRef<any>;
leaveDialogRef: MatDialogRef<any>;
constructor(
public _router: Router,
public dialog: MatDialog,
) { }
onLeave() {
this.leaveDialogRef = this.dialog.open(this.leaveDialog);
}
closeDialog() {
this.leaveDialogRef.close();
}
confirmLeave() {
this.closeDialog();
// Perform any necessary actions before leaving
this._router.navigate(['/other-page']);
}
محتوى الـ HTML:
<button (click)="onLeave()">Leave Page</button>
<ng-template #leaveDialog>
<h4>Confirm Leaving Page</h4>
<p>Unsaved changes will be lost. Are you sure you want to leave?</p>
<button type="button" (click)="closeDialog()">Cancel</button>
<button type="button" (click)="confirmLeave()">Leave Page</button>
</ng-template>
نموذج أفضل:
<ng-template #leaveDialog>
<div class="warn-border" [dir]="(translateService.currentLang === 'ar')?'rtl' : 'ltr'">
<h1 class="back-primary text-white" mat-dialog-title>{{'LABELS.CONFIRM_LEAVING_PAGE' | translate}}</h1>
<p mat-dialog-content class="mt-4">{{'WARNING.UNSAVED_CHANGES' | translate}}</p>
<div mat-dialog-actions class="text-center">
<button [mat-dialog-close]="true" class="back-accent mx-auto d-block text-white" mat-button mat-dialog-close
(click)="confirmLeave()"><span class="text-white">{{'BUTTONS.LEAVE_PAGE' | translate}}</span></button>
<button [mat-dialog-close]="false" class="back-primary mx-auto d-block text-white" mat-button
mat-dialog-close (click)="closeDialog()"><span class="text-white">{{'BUTTONS.CANCELE' |
translate}}</span></button>
</div>
</div>
</ng-template>
تعليقات
إرسال تعليق