How to keep data on screen by clicking the back button with Angular 8

Asked

Viewed 250 times

0

I am studying angular by implementing a small application of questionnaires I came across the following problem. when clicking the back button, I noticed that my selected options were gone, there is some way to keep these choices saved on the screen until I save the questionnaire??

my HTML

    <div class="content">
        <span class="etapas">Etapa 3 de 4</span>
        <h2>{{pergunta?.dsPergunta}}</h2>
        <p>Escolha até 3 opções</p>
        <div class="box-questoes">
            <ul>
                <li *ngFor="let res of pergunta.respostas" (click)="insereResposta(res.cdResposta)"
                        [ngClass]="respostas?.includes(res.cdResposta) ? 'active' : ''">
                    <p>{{res.dsResposta}}</p>
                    <small>{{res.dsAssunto}}</small>
                </li>
            </ul>
        </div>
        <button (click)="addPergunta()" [routerLink]="[ '/comentario']" class="btn-basico" [disabled]="respostas?.length === 0">Continuar</button>
        <a href="#" (click)="limpaRespostas()" [routerLink]="[ '/forma', cdPergunta, avaliacao]" class="link-bottom">Voltar</a>
    </div>
</div>
<ngx-ui-loader></ngx-ui-loader>

my TS

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PesquisaService } from 'src/app/services/pesquisa.service';
import { Pergunta } from 'src/app/models/pergunta';
import { Resposta } from 'src/app/models/resposta';

@Component({
  selector: 'app-questoes',
  templateUrl: './questoes.component.html',
  styleUrls: ['./questoes.component.scss']
})
export class QuestoesComponent implements OnInit {

  avaliacao: number;
  questoes: Resposta[];
  selecionado = false;
  pergunta: Pergunta;
  respostas: number[];

  cdPergunta: number;
  formaResposta: number;

  constructor(private route: ActivatedRoute, private pesquisaService: PesquisaService) {
    this.respostas = [];
    this.avaliacao = parseInt( this.route.snapshot.paramMap.get('avaliacao'));
    this.formaResposta = parseInt(this.route.snapshot.paramMap.get('formaResposta'), 10);

  }

  ngOnInit() {

      this.pesquisaService.getPerguntaResposta(3).subscribe(perguntaResponse => {
        this.pergunta = perguntaResponse;

        if(this.formaResposta == 14){
         this.pergunta.respostas = this.pergunta.respostas.filter(a => a.cdResposta != 12);
        }

        if(this.avaliacao <= 2){
          this.pergunta.dsPergunta = "O que MENOS você gosta?";
        }if(this.avaliacao >= 4){
          this.pergunta.dsPergunta = "O que MAIS você gosta?";

        }
      });
  }

  insereResposta(cdResposta: number) {
    if (this.respostas.includes(cdResposta)) {
      this.respostas.splice(this.respostas.indexOf(cdResposta), 1);
    } else if (this.respostas.length < 3) {
      this.respostas.push(cdResposta);
    }
    console.log(this.respostas);
  }

  addPergunta() {
    this.pesquisaService.addPergunta(this.pergunta.cdPergunta, this.respostas);
  }

  limpaRespostas() {
    this.pesquisaService.limpaRespostas();
  }

}
  • I don’t know if it would be the best solution, but thought about storing what you need in the browser’s localStorage or even creating a Singleton and storing the items you need? and then when entering the screen you want again, check if there are items stored in the localStorage or Singleton, as you prefer to do

  • what would be the site?

1 answer

1

The localStorage is a type of local browser storage, in it you store items in key-value.

We have some methods:

  1. setItem: set value for a key in your local storage

window.localStorage.setItem(chave, valor)

window.localStorage.setItem("nome", "Alexsandro")

  1. getItem: recover the previously defined value

window.localStorage.getItem(chave)

window.localStorage.getItem("nome") // retorna "Alexsandro"

  1. removeItem: remove the previously defined value

window.localStorage.removeItem(chave)

window.localStorage.removeItem("nome")

  1. clear: clean existing items in storage

window.localStorage.clear()


You could do something like:

const formulario = {
       nome: "Alexsandro",
       email: "[email protected]"
    };
    
window.localStorage.setItem("formulario", JSON.stringify(formulario));
var retorno = window.localStorage.getItem("formulario");
console.log(retorno);

I created an example in jsfiddle.

To view, if you’re using Google Chrome:

  • Open the Inspecionar
  • On the tabs, click Application
  • In the menu on the left side, click on LocalStorage
  • Click on the item that will appear below the LocalStorage

inserir a descrição da imagem aqui

  • valeu man! I will use your strategy, this working

Browser other questions tagged

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