Any examples on getting ngx-formly to work correctly with ngrx?

559 Views Asked by At

I'm trying to learn ngx-formly and ngrx for a project at work, does anyone know how to correctly get ngx-formly to bind/ update the ngrx store correctly?

I can get my data to initialize from the store using a selector, but everytime I either type in an input field or dropdown, I get

ERROR TypeError: Cannot assign to read only property 'purchaseType' of object

Formly's docs do not specifically mention anything for ngrx, but was wondering if anyone knows of any reposoitories on github or something that I can use as an example to figure out if there are any options or anything that I need to set to get it to work I am just not sure how Formly triggers the state change.

1

There are 1 best solutions below

0
On

Better late than never. Here's a few ideas that you could try:

Change your selector from this:

@Select(state => state.animals) animals$: Observable<any>;

To make a copy of the object instead:

@Select(state => structuredClone(state.animals)) animals$: Observable<any>;

Note that this should make the Select result mutable. If not, you'll need an alternative clone method. With a mutable copy ngx-formly should be able to work with the form as needed. Any changes to the state can be handled via hooks in your ngx-formly field configurations. Something like this:

key: 'firstName'
hooks: {
  onInit: (field: FormlyFieldConfig) => {
    field.form.get('firstName').valueChanges.subscribe(newName => {
      this.store.dispatch(new FirstNameChanged(newName);
    });
  },
},

You could also use @ViewChild to reference your form instead of watching individual fields:

@ViewChild(NgForm) form:NgForm;

ngAfterViewInit() {
  form.ValueChanges.subscribe(newValue => {
    this.store.dispatch(new MyAction(newValue));
  })
}  

Lastly, this is not tested, I'm presenting an idea that may help, but you'll need to work through the implementation details to fit your specific needs.