I'm trying to make a form like this;
<form #testForm="ngForm" (ngSubmit)="onSubmit(testForm)" novalidate>
<!-- X-Value -->
<div ngModelGroup="xValue" class="blocks">
<h3>XValue</h3>
<mat-radio-group name="value1" [(ngModel)]="data.xValue.value">
<mat-radio-button value="xValue1" class="child">xValue1</mat-radio-button>
<mat-radio-button value="xValue2" class="child">xValue2</mat-radio-button>
</mat-radio-group>
<textarea #text1 name="note1"[(ngModel)]="data.xValue.note"></textarea>
</div>
<!-- Y-Value -->
<div ngModelGroup="yValue" class="blocks">
<h3>YValue</h3>
<mat-radio-group name="value2" [(ngModel)]="data.yValue.value">
<mat-radio-button value="yValue1" class="child">yValue1</mat-radio-button>
<mat-radio-button value="yValue2" class="child">yValue2</mat-radio-button>
</mat-radio-group>
<textarea #text2 name="note2" [(ngModel)]="data.yValue.note"></textarea>
</div>
</form>
the values for this form are tied to a model in my ts file which I initialise like this;
data= {
xValue: {
value: "xValue1",
note: ""
},
yValue: {
value: "yValue1",
note: ""
},
}
defaultObj= JSON.parse(JSON.stringify(this.data));
initially I have to check an api to see if the form has been stored before, if yes then I have to show the previously stored form. For that I copy the object I received to this.data and the form loads the correct values. If there are no values then I have to show the default values, which is why I stored data into defaultObj.
apiCall(){
this.data= JSON.parse(JSON.stringify(this.existingFormValuesFromApi));
}
This shows me the correct data on page load if there are saved values. The issue is when the user cancels the edits, the form should be reset to existingFormValuesFromApi.
I tried to do this;
//TS file
this.testForm.setValue(this.existingFormValuesFromApi)
but that also throws an error in the browser saying that I must provide a value for value1.
How does that work? How is the initial value being loaded correctly? Why are changes to my data object also reflecting to my existingFormValuesFromApi object?
EDIT: Nested objects cannot be copied without reference using any of the methods, assign(), create() or using the spread operator; since I used only nested objects in my data object the changes made to data would reflect in allmy nested objects as well. As seen here.