The following code will make browser to ask user that whether he wants to lose the unsaved changes or not.
Also, I'm checking whether the form is dirty or not.
If the form is not dirty, browser won't bother the user and close it.
import { Component, ViewChild, HostListener } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DetailedUser } from 'src/app/models/detailed-user';
@Component({
selector: 'app-member-edit',
templateUrl: './member-edit.component.html',
styleUrls: ['./member-edit.component.css']
})
export class MemberEditComponent {
user: DetailedUser = new DetailedUser();
@ViewChild('userForm') userForm: NgForm;
@HostListener('window:beforeunload', ['$event'])
WindowBeforeUnoad($event: any) {
if (this.userForm.dirty) {
$event.returnValue = 'Your data will be lost!';
}
}
saveChanges(){
....
this.userForm.reset(this.user);
}
}
the following is the html section
<form (ngSubmit)="saveChanges()" #userForm="ngForm">
<div class="form-group">
<label for="introduction">Introduction</label>
<textarea
name="introduction"
class="form-control"
[(ngModel)]="user.introduction"
rows="6"></textarea>
</div>
<div class="form-group">
<label for="lookingFor">Looking For</label>
<textarea
name="lookingFor"
class="form-control"
[(ngModel)]="user.lookingFor"
rows="6"></textarea>
</div>
</form>