Angular Signal computed functionality doesn't update the number of item an array contain

1.7k views Asked by At

I have this service

itemList= signal<Item[]>([]);
reset(){
   this.itemList.set([]);
}
add(item){
 this.itemList.update(list => {
  const ind = list.findIndex(o => o._id == item._id);
  if (ind !== -1) {
    list.splice(ind, 1);
  } else {
    list.push({_id:item._id,name:item.name});
  }
  list.sort((a, b) => a.name > b.name ? 1 : a.name === b.name ? 0 : -1);
  return list;
})
}
itemCount = computed(() => this.itemList().length);

reset function and add item is working as expect but the itemCount is not updating, it is always ZERO.

I tried by accessing the service directly in the html : service.itemCount() and it doesn't work. What I'm doing wrong ?

However, if I use service.itemList().length it works.

UPDATE

Please find the issue with angular 17 here.

2

There are 2 answers

1
Caio Oliveira On

If you don't change the reference, angular will assume the value hasn't changed, and won't update

Just change your return value on update to return a new value

return [...list];
0
tsimon On

Caio is correct: there was a last-minute change to the signals API that made in-place mutations no longer work. For a more detailed answer, you can see my response here.