Astrix
February 12, 2018, 5:56pm
1
I have this code in .html :
<ion-label floating>First Name</ion-label>
<ion-input type="text" [(ngModel)]="userData.firstName"></ion-input>
in ts:
userData = {'firstName': '', 'lastName': '', 'phoneNumber': '', 'emailAddress': ''};
saveChange(){
localStorage.setItem('userData', JSON.stringify(this.userData));}
How can i have my input section have text (that was saved in local storage) upon reloading the page?
What I want in practice:
I type all the needed infos, i hit saveChanges - upon realoading the page the input sections gets the written datas automatically. Upon change, the changed values are written in them.
Thanks in advance.
Nexi
February 12, 2018, 9:09pm
2
I would prefer storage from ionic (https://ionicframework.com/docs/storage/ ), but this should work for localstorage.
Example on StackBlitz:
home.html
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form #userForm="ngForm">
<ion-item>
<ion-label floating>First Name</ion-label>
<ion-input type="text" name="firstName" [(ngModel)]="userData.firstName"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Last Name</ion-label>
<ion-input type="text" name="lastName" [(ngModel)]="userData.lastName"></ion-input>
</ion-item>
</form>
</ion-content>
home.ts
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { NavController } from 'ionic-angular';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('userForm') form: NgForm;
storageSub: Subscription;
userData = {
firstName: '',
lastName: ''
};
ionViewDidLoad() {
const localData = localStorage.getItem('userData');
try {
if (localData) {
this.userData = JSON.parse(localData);
console.log('Data loaded', localData);
}
} catch (error) { }
// If not delayed, it will unnecessarily save the loaded files
setTimeout(() => {
this.storageSub = this.form.valueChanges.subscribe(userData => {
localStorage.setItem('userData', JSON.stringify(userData));
console.log('Data saved', JSON.stringify(userData));
});
}, 0);
}
ionViewWillUnload() {
this.storageSub.unsubscribe();
}
}
1 Like
Astrix
February 13, 2018, 8:39am
3
Thank you very much!
It works perfectly!