1

How can I save and keep the dropdown value of the dropdown item of PrimeNG after page refresh ?

https://www.primefaces.org/primeng/#/dropdown

HTML

<p-dropdown [options]="cities2" [(ngModel)]="selectedCity2" optionLabel="name"></p-dropdown>

TypeScript

   import {SelectItem} from 'primeng/api';

    interface City {
      name: string;
      code: string;
    }

    export class MyModel {
        cities2: City[];
        selectedCity2: City;

        constructor() {
            //An array of cities
            this.cities2 = [
                {name: 'New York', code: 'NY'},
                {name: 'Rome', code: 'RM'},
                {name: 'London', code: 'LDN'},
                {name: 'Istanbul', code: 'IST'},
                {name: 'Paris', code: 'PRS'}
            ];
        }
       ngOnInit(){
        localStorage.setItem('key', this.selectedCity2);
        const getItem = localStorage('key');
        this.selectedCity2 = getItem;


    }
Antikhippe
  • 6,316
  • 2
  • 28
  • 43
Noah Tony
  • 373
  • 3
  • 7
  • 18

1 Answers1

-1

First of all, to set (or get) a javascript object in (or from) localStorage, use JSON.stringify (or JSON.parse) method.

Then, in ngOnInit method, you should only get the value stored in your localStorage and you must not update it as it is in your code.

So this method becomes :

  ngOnInit() {
    // get localStorage value
    this.selectedCity2 = JSON.parse(localStorage.getItem('key'));
  }

Finally, everytime you select an item in your dropdown element, you have to update its value in the localStorage like that :

  saveInLocalStorage() {
    // update localStorage value
    localStorage.setItem('key', JSON.stringify(this.selectedCity2));
  }

See StackBlitz

Antikhippe
  • 6,316
  • 2
  • 28
  • 43
  • Hi, I just tried it out in my applicaition and I am getting following error warn argument of type string | object is not assignable to parameter of type string. Type OBject is not assignable to type string. If I delete JSON.parse then the warning will be not shown but it is not working then – Noah Tony May 22 '18 at 09:24
  • Ok, after save into localstorage the data looks like this if I get it: {'key:1, name:'Ney York', type:0, validFrom:"2002-01-01T00:00:00.000Z"} but still not working – Noah Tony May 22 '18 at 12:02
  • Did you add `(onChange)="saveInLocalStorage()"` in your HTML ? – Antikhippe May 22 '18 at 12:08
  • Thtat's already saved in localstorage, you should not save that again. – alecellis1985 May 31 '20 at 16:58
  • No, it isn't. PrimeNG does not save data in your localstorage for you. It's your job to do it. – Antikhippe May 31 '20 at 17:05