1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Can I tell angular to do immutable property changes while using two way binding?

Discussão em 'Angular' iniciado por Jan, Setembro 25, 2024.

  1. Jan

    Jan Guest

    I have to deal with complex DTOs but would still like to edit a property using two way binding.

    // BAD
    <my-component [(value)]="myfield.propertya.propertyb" />


    If I do so, I would mutate the original object. Angulars change detection would not understand the change.

    Doing it correctly as an immutable update, I need to write an update method for each property:

    // GOOD BUT BULKY
    <my-component [value]="myfield.propertya.propertyb"
    (valueChange)="changePropertyAPropertyB($event)" />

    changePropertyAPropertyB(value) {
    myfield = { ...myfield, propertya: { ...myfield.propertya, propertyb: value } }
    }

    // or simplified with immerjs
    changePropertyAPropertyB(value) {
    myfield = produce(myfield, draft => { draft.propertya.propertyb = value })
    }


    Is there a way to do so without an extra method for each property?

    With model signals I still have the same problem.

    NGRX Signal State allows deep reads like [value]="mySignalState.propertya.propertyb()". But updating it, I still need a to create a bulky patchState method

    changePropertyAPropertyB(value) {
    patchState(mySignalState,
    (state) => ({ propertya: { ...state.propertya, propertyb: 'Jimi' } })
    );
    }


    Is there a concise and simple way that works well with the angular change detection?

    Continue reading...

Compartilhe esta Página