Change color of item on click Angular

194 Views Asked by At

I have a list, when I click on an item I would like to change the color of this item.

I dit this :

html

[ngStyle]="{'color': item.isClicked ? 'grey': ''}"

ts

  itemSelected(item) {
    if (item.isClicked) {
      item.isClicked = true;
    } else {
      item.isClicked = true;
    }
    this.router.navigate(['/details', { data: JSON.stringify(item) }]);
  
   }

it works but when I refresh the page it doesn't work. how do I persist ?

thanks for your help !

2

There are 2 best solutions below

1
On

You can save the item in local storage before you leave the page. And restore the item from the local storage when the component is initiated:

ngOnInit() {
  try {
    this.item = JSON.parse(localStorage.getItem('item'));
  } catch (err) {}
}
...
itemSelected(item) {
  if (item.isClicked) {
    item.isClicked = true;
  } else {
    item.isClicked = true;
  }
  const data = JSON.stringify(item);
  localStorage.setItem('item', data);
  this.router.navigate(['/details', { data }]);
}
0
On

You need to store that information in session storage or local storage (If you want more persistency instead of just page refresh).

Moreover please review your code once. You are checking if item.isclicked is true and again assigning it true. Same in else block.