I made a multi select component that has an input() signal to set an Array of selectable options. I also have a writable signal to track which options have been selected. How do I clear the writable signal once the input of selectable options have been changed?
The only solution I can think of is an effect but the docs say that you should not write to signals in an effect. Is this even possible with the effects API or do I have to rewrite my component with ngOnChanges and traditional Input selectors?
import { Component, computed, effect, EventEmitter, input, Output, signal } from '@angular/core';
export interface MultiSelectGroupOption {
id: number;
title: string;
}
@Component({
selector: 'app-multi-select-group',
templateUrl: './multi-select-group.component.html',
})
export class MultiSelectGroupComponent {
public maxSelectedItems = input<number>(1);
public options = input<Array<MultiSelectGroupOption>>([]); // when this changes selectedItems needs to be reset
public selectedItems = signal<Array<MultiSelectGroupOption>>([]);
@Output()
public selectionChange = new EventEmitter<Array<MultiSelectGroupOption>>();
public constructor() {
effect(() => {
this.selectionChange.emit(this.selectedItems());
});
}
public selectItem(item: MultiSelectGroupOption): void {
this.selectedItems.set([...selectedItems, item]);
}