Search code examples
angulartypescriptlocal-storageprimengprimeng-dropdowns

Save and keep dropdown values after page refresh PrimeNG


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;


    }

Solution

  • 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