How best to avoid excessive spread operator usage when updating Signal Objects?

Discussão em 'Angular' iniciado por monkey, Março 20, 2025.

  1. monkey

    monkey Guest

    I am starting to use Angular signals and in general they bring immense benefits. However, I am finding myself writing more and more horrible update functions because of the immutabilty issue. For example,

    /** Input & Output Interface */
    export interface MonkeyShowOnlyOptions {
    categoryArray?: {
    categoryName: string;
    values?: {
    name: string;
    icon?: string;
    selected?: boolean;
    }[];
    }[];
    }

    ...

    /** Clear Category Button Handler */
    onClear(cat: string) {
    console.log(`Clear all ${cat}`);

    this.searchParams.update(x => ({
    ...x,
    categoryArray: x.categoryArray?.map(category =>
    category.categoryName === cat
    ? {
    ...category,
    values: category.values?.map(item => ({
    ...item,
    selected: false, // Set all selected values to false
    })),
    }
    : category
    ),
    }));
    }

    /** Invert Selection Button Handler */
    valueChange(cat: string, value: string) {
    console.log(`update for ${cat}:${value}`);
    this.searchParams.update(x => ({
    ...x,
    categoryArray: x.categoryArray?.map(category =>
    category.categoryName === cat
    ? {
    ...category,
    values: category.values?.map(item =>
    item.name === value
    ? { ...item, selected: !item.selected }
    : item
    ),
    }
    : category
    ),
    }));
    }


    Everything here works just fine, but I really hate the gnarly spread operator & map mess! Is there a better approach that we should follow to keep things cleaner?!

    Continue reading...

Compartilhe esta Página