1

页面刷新后如何保存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;


    }
4

1 回答 1

-1

首先,要在(或从)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

于 2018-05-21T13:54:27.837 回答