store icon indicating copy to clipboard operation
store copied to clipboard

Binding to State - is this expected behaviour?

Open garthmason opened this issue 8 years ago • 4 comments

Versions

* ngxs: 3.0.1
* @angular/core: 6.0.0

Repro steps

I have a state that contains a collection of items:

import { State, Action, StateContext } from '@ngxs/store';
import {AddItem} from './app.actions';

export interface Item { 
  id: number;
  name: string;
}

export interface AppStateModel { 
   items: Item[];
}

@State<AppStateModel>({
  name: 'app',
  defaults: {
    items: []
  }
})
export class AppState { 

  @Action(AddItem)
  addItem(ctx: StateContext<AppStateModel>, action: AddItem){
     const state = ctx.getState();

        ctx.patchState({
            items: [
                ...state.items,
                { id: action.id, name: action.name}
            ]
        });
  }

}

My component is subscribed to the list of items in the store, when I add a new item that is reflected in the list displayed (all fine).

Observed behavior

I then bind that displayed item to an input field - when I type in that input field I seem to be modifying the state of that item, i.e. the 'View Name' display of the item is also changing.

<ng-container *ngIf="app$ | async as app">

Name: <input #name />
<button (click)="addItem(name.value)">Add Item </button>

<br/>
<br/>

Items List:

<div *ngFor="let item of app.items">
  View Name: <span>{{item.name}}</span>
</div>

<br/>

Items List 2 with updates:

<div *ngFor="let item of app.items">
  Update Name: <input [(ngModel)]="item.name" />
</div>

</ng-container>

image

Desired behavior

Is this expected behaviour? I was expecting that I would not see that change reflected in the 'view only' list.

Or is this just a case of me doing something I shouldn't be - I know I should really be dispatching that change via an action to the store like this:

Update Name: <input [ngModel]="item.name" (ngModelChange)="updateItem(item.name)" />

updateItem(value) {
   this.store.dispatch(new UpdateItemAction(value));
}

Mention any other details that might be useful (optional)

See full sample repo here https://github.com/garthmason/ngxs

Thanks!

garthmason avatar May 09 '18 06:05 garthmason

Please ask this question on stackoverflow instead.

https://stackoverflow.com/questions/tagged/ngxs

leon avatar May 09 '18 06:05 leon

Sure, thought this might've been a bug so posted it here first - i'll raise on SO now. Thanks.

garthmason avatar May 09 '18 06:05 garthmason

We keep tabs on stackoverflow, so if we conclude that the question is a bug, we can add it to github later :)

leon avatar May 09 '18 07:05 leon

No problem @leon 👍

garthmason avatar May 09 '18 07:05 garthmason