Is there a way to cache a unfinished form when the page is leaved? When I go to the form and suddenly I try to put some data on each input field and when I leave that page the input field is cleared.
I used navCtrl.push
to go to that page where I want to create a POST.
I also used formBuilder
of Angular forms to structure my form model.
How can I do that?
Appreciate if someone could help.
I have solved the problem by creating a function in a provider to check and loop through the formBuilder object. If one field has an existing value a alert controller will pop up if the user wants to leave. If not it will proceed to leave the page.
Here is the code below:
in your page
async ionViewCanLeave() {
const formObj = this.form.value
if (!this.done) await this.alertMsg.allowUserToLeaveForm(formObj)
}
in the provider
allowUserToLeaveForm(formObject) {
const lengthChecker = formObject
const vals = Object.keys(lengthChecker).map((key) => lengthChecker[key].length)
const checkArr = vals.some(field => field > 0)
if (checkArr) {
return new Promise((resolve, reject) => {
const confirm = this.alertCtrl.create({
subTitle: 'Are you sure you want to leave the page?',
title: 'Your changes will not be saved',
enableBackdropDismiss: false,
buttons: [
{
text: 'No',
handler: () => {
reject();
}
},
{
text: 'Yes',
handler: () => {
resolve();
}
}
]
});
confirm.present();
});
}
}