skip to Main Content

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


  1. 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.

    import { createSignal, SIGNAL, signalSetFn } from '@angular/core/primitives/signals';
    
    function setSignal<T>(initial?: Iterable<T> | null | undefined) {
      const store = new Set<T>(initial);
      const $output = createSignal(store.values());
      const outputNode = $output[SIGNAL];
      return Object.assign($output, {
        add: (value: T) => mutate(store.add.bind(store, value)),
        clear: () => mutate(store.clear.bind(store)),
        delete: (value: T) => mutate(store.delete.bind(store, value)),
        has: store.has.bind(store)
      });
    
      function mutate(mutator: () => void) {
        mutator();
        signalSetFn(outputNode, store.values())
      }
    }
    

    Concerns

    • One thing I wonder about is if Array.from(store) would be better than using store.values() when writing to the signal.
    • Because a new value is getting stored with every mutatation, effect will get fired even if the value doesn’t change. One way to address this would be to change the mutate function so it only calls signalSetFn when the length of store has changed.

    Usage

    const $options = setSignal(['initialOption1']);
    console.log($options()); // SetIterator {'initialOption1'};
    $options.add('opt2');
    console.log($options()); // SetIterator {'initialOption1', 'op2'};
    $options.add('opt2');
    console.log($options()); // SetIterator {'initialOption1', 'op2'};
    $options.delete('initialOption1');
    console.log($options()); // SetIterator {'op2'};
    
    Login or Signup to reply.
  2. 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:

    dictionary = signal<Record<string, true>>({});
    
    toggleOption(option: string): void {
      if (!this.dictionary[option]) {
        this.dictionary.update((dictionary) => ({
          ...dictionary,
          [option]: true,
        }));
      } else {
        const dictionaryCopy = { ...this.dictionary() };
        delete dictionaryCopy[option];
        this.dictionary.update(() => dictionaryCopy);
      }
    }
    

    If this isn’t triggered a lot and performance doesn’t really matter, you could even just use an array

    values = signal<string[]>([]);
    
    toggleOption(option: string): void {
      if (this.values().includes(option)) {
        this.values.update((values) => values.filter((x) => x !== option));
      } else {
        this.values.update((values) => [...values, option]);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search