页面刷新PrimeNG后保存并保持下拉值

时间:2018-05-21 13:11:08

标签: angular typescript local-storage primeng primeng-dropdowns

如何在页面刷新后保存并保留PrimeNG下拉列表的下拉值?

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

HTML

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

打字稿

   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;


    }

1 个答案:

答案 0 :(得分:0)

首先,要在(或从)localStorage中设置(或获取)javascript对象,请使用JSON.stringify(或JSON.parse)方法。

然后,在ngOnInit方法中,您应该只获取存储在localStorage中的值,并且不得像在代码中那样更新它。

所以这个方法变成了:

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

最后,每当您在下拉列表元素中选择一个项目时,您必须在localStorage中更新其值:

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

请参阅StackBlitz