IleNea
IleNea

Reputation: 609

Angular 2 sessionStorage after session storage set the current value not modified

I need some help about a sessionStorage problem.

When I change a value from a dropbox, it changes on the page, but after I click on another page and come back the value is not save. So what I've done:

handleOnItemsPerPage(itemsPerPage) {

  sessionStorage.setItem('itemsPerPage', JSON.stringify(itemsPerPage));

  this.onFilter.emit({
    items: this.cachedItems,
    field: 'type',
    type: this.selectedCategory,
    query: this.searchQuery,
    itemsPerPage: parseInt(itemsPerPage, 10),
    sortAsc: this.isAscSort,
    page: this.page
  });
}

When I change the value, I save it in session Storage, so when I come back to display it. So in my ngInit:

ngOnInit() {
   this.sessionStorage =  JSON.parse(sessionStorage.getItem('itemsPerPage'));
}

And in html:

<app-pager [pagedItems]="pagedItems"
[itemsPerPage]="sessionStorage ? sessionStorage : itemsPerPage"
[page]="page"
(onPageChange)="handleOnPageChange($event)"
(onItemsPerPage)="handleOnItemsPerPage($event)">
</app-pager>

The problem is that the first time is working, if I change the value and come back on the page it applies the changes, but after I change again the value, it doesn't change to the current value, but the session one.

How exactly to fix this? Thank you.

Upvotes: 0

Views: 1994

Answers (1)

Swoox
Swoox

Reputation: 3740

It will only change on a reload simple cause then the ngOnInit is tiggered. If you want to change the value you have to change it and store the value.

sessionStorage.setItem('itemsPerPage', JSON.stringify(itemsPerPage));
this.sessionStorage =  itemsPerPage;

If you want to know why the two-way binding is not working try:

let a = 10;
let b = JSON.parse(JSON.stringify(a));

Normally if you do let b = a; and then change a b will be changed to, but now you can change a and b will not change. We call this a deep copy.

Upvotes: 0

Related Questions