How to define only changed fields in Angular 2 forms?

I am using FormGroup and FormControls toghether with ngrx to create a reactive form. I also use Chrome Inspector redux redux dev-tools . I want to correctly display the history of actions, skipping some actions to change the form. An action of any shape is being skipped before the latter is projected as if this change to a specific shape had not been made. The form submits the complete object with all applicable fields. Thus, any change to previous actions is obscured, since each action replaces all previous properties of the form state.

A bit of context: I put a person object in the state store while the user fills out the form inside the modal. Then on submit I send the person data to the server.

Form component

 // Emit events when form changes this.personForm.valueChanges .debounceTime(500) .subscribe(person => { // Block @Input person update from triggering a form change if (this._personFormInputUpdated === true) { // Reset @Input safe-guard this._personFormInputUpdated = false; return; } // Ignore unchaged form if (!this.personForm.dirty) { return; } debug('Person form changed'); this.personChange.emit(Object.assign({}, person)); }); 

Gearbox:

  case AccountsDataActions.STASH_ACCOUNT_PERSON: newState = Object.assign({}, state, { stashedAccountPerson: Object.assign({}, state.stashedAccountPerson, action.payload) }); debug('STASH_ACCOUNT_PERSON:', [newState.stashedAccountPerson]); return newState; 

I am considering using some kind of difference checking library to select only the changed fields for the next STASH_ACCOUNT_PERSON action. Is there a simpler method that does not require an additional library? Something built into ng2 forms?

Thanks!

Edit ngOnChanges() has a similar effect for @Input decorators. Is there something similar for forms?

+6
source share
2 answers

Yes. try using the differUntilChanged method . Returns an observable sequence containing only individual adjacent elements according to the key and filter.

 this.personForm.valueChanges .debounceTime(500) .distinctUntilChanged() .subscribe(person => { // only what changed! }); 
+1
source

You can watch KeyValueDiffers and KeyValueDiffer at @angular/core

0
source

Source: https://habr.com/ru/post/1014915/


All Articles