0

Hi I have a form in Angular, that i build with values from an Observable from API.

.subscribe((res) => {
this.data = res['attributes'];
});

//this.data is array of objects!!

this.attribs = modifyClean(this.data);
this.attribsOriginal = this.attribs;
Object.freeze(this.attribsOriginal);

After the form is built with this.attribs. If the user edits its original form values and Clicks save, the api saves it. But if the API fails to save (500 error or something) I want the form to go back to its original values. I am not using Reactive forms on purpose. But here is what i am doing when the api fails in error code

,error {
 this.attribs = this.attribsOriginal;
}

But this is not replacing the form values with original values. It is retaining the values. I console.log both this.attribs and this.attribsOriginal in error block. Both of them are same values. How is this possible. I froze attribsOriginal. If i say this.attribs = []; the form is completely removed as expected. But why doesnt this.attribs = this.attribsOriginal, replace the form values with orginal values. I thought freezing this.attribsOriginal will have no impact no matter what you do to this.attribs. what can be done to avoid this situation?

Santy
  • 13
  • 3

1 Answers1

0

It looks like this.attribs is a reference to data returned by modifyClean(this.data), and this.attribsOriginal is also a reference to the same data. If you're trying to clone an object this looks helpful

Angular uses change detection to decide when to build/rebuild the portion of the dom using your "this.attribs" data. Since nothing is changing it isn't building/rebuilding the dom.

I think you could try arbitrarily changing the data in the component.ts file, and changing it back, or this might be helpful

Ben
  • 80
  • 7
  • I tried all possibilities. I tried your suggestions too.. The problem why the object deep clone or freeze or any method didnt work is I am using ngModel for each field value. I think that is changing the original reference of the array of objects that is originally used to build the form. Literally any method didnt work. Tried RXjs observables, to store the initial value in a behavior subject.. that didnt work too. I didnt even change the subject with next operator. I only used it once when i receive the api data. But still ngModel changed the behavior subject array of objects values. – Santy Nov 06 '19 at 22:04
  • Finally Finally Finally one method worked.. which is.. I used crypto-js to encrypt and decrypt the value to replace the original this.attribs value. – Santy Nov 06 '19 at 22:04
  • if you write [(ngModel)] in your template (with the square and round brackets) then that tells angular to use 2-way binding and it'll change the objects like you say. But you can just write it with no brackets, like , and that way data will only flow from component.ts to the template, and not backwards. – Ben Nov 07 '19 at 01:10