angularngrx-storengrx-forms

ngrx-form, ngrx-store, change value programmatically


I have the following reducer.ts

export const FORM_ID = 'doctransForm';

export interface FormValue {
  erstellt: string;
}

export const INITIAL_STATE = createFormGroupState<FormValue>(FORM_ID, {
  erstellt: ''
});

export interface State {
  entities: DoctransEntity[];
  errorMessage: string;
  loading: DataState;
  formState: FormGroupState<FormValue>;
}

export const doctransInitialState: State = {
  entities: [],
  errorMessage: null,
  loading: DataState.LOADED_STATE,
  formState: INITIAL_STATE
}

const _doctransReducer = createReducer(
  doctransInitialState,
  onNgrxForms(),
  on(formValueChange, (state, { type, ...update }) => ({ ...state, ...update })),
  on(DoctransActions.resetForm, (state, action) => ({ ...state, formState: INITIAL_STATE })),
  on(DoctransActions.setErstellt, (state, action) => ({ ...state, formState: { ...state.formState, value: { ...state.formState.value, erstellt: action.erstellt} }})),
);

export function doctransReducer(state: State, action: Action) {
  return _doctransReducer(state, action);
}

An input-field in html:

<input [ngrxFormControlState]="doctransFormState.controls.erstellt">

Now i just want to simply change the value programmatically.

I tried the following:

this.store.dispatch(setErstellt({erstellt: 'lala test'}));

    const control = createFormControlState<string>('doctransFormState.controls.erstellt', '');
    const updatedControl = setValue('new Value1')(control);
    const updatedControlUncurried = setValue(control, 'newValue2');
    const updatedControlViaAction = formStateReducer(control, new SetValueAction(control.id, 'newValue3'));

But nothing works. It seems i dont understand how to use the setValue from here: https://ngrx-forms.readthedocs.io/en/master/user-guide/updating-the-state/#setting-the-value

Can anyone help out?


Solution

  • Finally. Got it:

    this.store.dispatch(new SetValueAction('doctransForm.erstellt', 'newValue3'));