new Set () with Angular signals

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!

3

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'};

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]);
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật