I was wondering how to use a new Set ()
javascript’s object with Angular "new" Signals. As I’ve been a long time playing with it, I decided to post it in here. Just a simple adding and deleting.
set = signal (new Set ()); // initialize as an empty set, no need the <Set> because it's implicit.
toggleOptionFromSet (option: string) { // just a function to toggle an option in and out of a signal Set.
if (this.set ().has (option)) { // if the set contains the value...
this.set.update (set => { // deletes the option of the set.
// you cannot return set.delete (option) because it returns a boolean and update needs to return a Set.
set.delete (option)
return set;
});
console.log (this.set ()); // you see that the option has been erased.
} else { // if the set () does not contain the option...
this.set.update (set => set.add (option)); // this actually returns a new set, so, as you might know, you don't need to return it explicitly.
console.log (this.set ()); // the option has been added to the set.
}
}
Hope it helps someone!
2
Answers
If you want, you can create your own setSignal. The example below will create a signal that returns the values of a Set. The signal is updated through functions that are assigned to the signal and mirror the functions of Set. An mutate function keeps the output signal and Set store in sync.
Concerns
Array.from(store)
would be better than usingstore.values()
when writing to the signal.Usage
As pointed out by Matthieu Riegler, this won’t trigger any reactivity.
As there’s no such native data structure as an immutable
Set
, I think a better approach would simply be to use an object (that you never mutate) like this:If this isn’t triggered a lot and performance doesn’t really matter, you could even just use an array