How to fill input from localstorage

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': ''};

    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.

I would prefer storage from ionic (, but this should work for localstorage.

Example on StackBlitz:



<ion-content padding>
  <form #userForm="ngForm">
      <ion-label floating>First Name</ion-label>
      <ion-input type="text" name="firstName" [(ngModel)]="userData.firstName"></ion-input>
      <ion-label floating>Last Name</ion-label>
      <ion-input type="text" name="lastName" [(ngModel)]="userData.lastName"></ion-input>


import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { NavController } from 'ionic-angular';
import { Subscription } from 'rxjs/Subscription';

  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() {


1 Like

Thank you very much!
It works perfectly!