Save data from an offline input

Asked

Viewed 91 times

0

Good afternoon, I’m trying to save the data (with Localstorage) from an input into a variable, but I’m not getting it right. The page itself is an option to Save user data.

Follow the . html

   <ion-item>
     <ion-label position="Fixed">Nome</ion-label>
     <ion-input [(ngModel)]="nome">{{nome1}}</ion-input>
   </ion-item>
 <ion-button expand="block" (click)="saveInformations()">Salvar</ion-button>

Follow the . ts

  nome : string; 
  nome1: string;

  saveInformations(){

    localStorage.setItem('nome', this.nome);

    this.nome1 = this.nome

  }


ngOnInit() {

    localStorage.getItem(this.nome)
  }

When I leave the page and come back the input appears blank, what I’m doing wrong?

  • No, but what about the getItem('name') ???

  • Whoa, I forgot to put the whole code.

1 answer

2


The value of the input was saved in localStorage but you are not reading and filling your input with this value when your component is initialized.

Example:

nome : string; 
nome1: string;

ngOnInit() {
    this.nome1 = localStorage.getItem('nome') || '';
}

saveInformations() {
    localStorage.setItem('nome', this.nome);
    this.nome1 = this.nome
}
  • This way it even works, but the fields that have not been filled in, appears Undefined

  • I managed to solve it this way if (this.nome == undefined ){&#xA; this.nome1 = ''&#xA; } else {&#xA; localStorage.getItem('nome');&#xA; } but in html it repeats the input twice, can help me in this case?

  • @rzp You can remove the variable nome1 and use only the nome. Change the component to: <ion-input [(ngModel)]="nome"></ion-input> and adjustment in ngOnInit to populate the variable nome instead of nome1. This should work. If it doesn’t work just say ;) abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.