Update two signals which depends on each other in abgular

Discussão em 'Angular' iniciado por vitaly, Março 26, 2025.

  1. vitaly

    vitaly Guest

    What is the best way to work with signals that depend on each other in angular?

    Here are the example

    export class SomeComponent<TItem> {

    fieldName = input<string>('name', { alias: 'field-name' });
    fieldValue = input<string>('id', { alias: 'field-value' });

    // List of items
    items = input<TItem[]>([]);

    // currently selected items
    item = model<TItem>();

    // currently selected value
    value = model<unknown>();

    // HERE SHOULD BE SOME LOGIC TO CALL BELOW METHODS


    /*
    * I have below methods which fire and update dependent
    * values
    * e.g. update value when item changed
    * update item when value changed
    * update both value and item when items are changed
    */
    onItemChanged() {
    const item = this.item() as Record<string, unknown>;
    // TODO: check if values are equal to avoid circular dependency
    this.value.set(this.fieldValue() && item ? item[this.fieldValue()] : item);
    }

    onValueChanged() {
    const items = this.items() as Record<string, unknown>[];
    const item = items.find(i => this.getValue(i) == this.value());
    // TODO: check if items are equal to avoid circular dependency
    this.item.set(item as TItem);
    }

    onItemsChanged() {
    //Try to find the item by value in a new items list
    const items = this.items() as Record<string, unknown>[];
    const item = items.find(i => this.getValue(i) == this.value());
    this.item.set(item as TItem);

    // probably can be omitted as will be handled in onItemChanged
    if (item == undefined)
    this.value.set(undefined);
    }

    getValue(obj: Record<string, unknown>|undefined): unknown {
    const field = this.fieldValue();
    return field && obj ? obj[field] : obj;
    }

    }


    I can implement this with the next approaches (calling on..Changed method in next hooks):

    • move back to @Input decorator (make a setter)
    • ngOnChange (handle model updates here )
    • effects, this is the most elegant but this approach angular team does not recommend using for updating dependent values (they at all do not recommend using effects except in rare cases)
    • linkedSignal (it requires the introduction of additional members, but this can be done)
    • Convert a signal to observable and subscribe but under the hood angular use effects, so no differences from using effects??

    So what is the best and most elegant way to implement such dependencies?

    Thank you

    Continue reading...

Compartilhe esta Página