|
| 1 | +import { Component, inject } from '@angular/core'; |
| 2 | +import { patchState, signalStore, withMethods } from '@ngrx/signals'; |
| 3 | +import { withImmutableState } from '@angular-architects/ngrx-toolkit'; |
| 4 | +import { MatButton } from '@angular/material/button'; |
| 5 | +import { FormsModule } from '@angular/forms'; |
| 6 | + |
| 7 | +const initialState = { user: { id: 1, name: 'Konrad' } }; |
| 8 | + |
| 9 | +const UserStore = signalStore( |
| 10 | + { providedIn: 'root' }, |
| 11 | + withImmutableState(initialState), |
| 12 | + withMethods((store) => ({ |
| 13 | + mutateState() { |
| 14 | + patchState(store, (state) => { |
| 15 | + state.user.id = 2; |
| 16 | + return state; |
| 17 | + }); |
| 18 | + }, |
| 19 | + })) |
| 20 | +); |
| 21 | + |
| 22 | +@Component({ |
| 23 | + template: ` |
| 24 | + <h2> |
| 25 | + <pre>withImmutableState</pre> |
| 26 | + </h2> |
| 27 | + <p> |
| 28 | + withImmutableState throws an error if the state is mutated, regardless |
| 29 | + inside or outside the SignalStore. |
| 30 | + </p> |
| 31 | + <ul> |
| 32 | + <li> |
| 33 | + <button mat-raised-button (click)="mutateOutside()"> |
| 34 | + Mutate State outside the SignalStore |
| 35 | + </button> |
| 36 | + </li> |
| 37 | + <li> |
| 38 | + <button mat-raised-button (click)="mutateInside()"> |
| 39 | + Mutate State inside the SignalStore |
| 40 | + </button> |
| 41 | + </li> |
| 42 | + </ul> |
| 43 | +
|
| 44 | + <p>Form to edit State mutable via ngModel</p> |
| 45 | + <input [(ngModel)]="userStore.user().name" /> |
| 46 | + `, |
| 47 | + imports: [MatButton, FormsModule], |
| 48 | +}) |
| 49 | +export class ImmutableStateComponent { |
| 50 | + protected readonly userStore = inject(UserStore); |
| 51 | + mutateOutside() { |
| 52 | + initialState.user.id = 2; |
| 53 | + } |
| 54 | + |
| 55 | + mutateInside() { |
| 56 | + this.userStore.mutateState(); |
| 57 | + } |
| 58 | +} |
0 commit comments