I have a component that displays some data on a page from a subscription.
I am trying to clone this variable and make changes to it without affecting the original data used to render the page view.
import { UtilsService } from '../shared'; import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-review', templateUrl: './review.component.html', styleUrls: ['./review.component.css'] }) export class ReviewComponent implements OnInit { @Input() payload: any = null; // Object of strings that are used for the details langStr: any = { noDepartment: 'No Department Change', noSegment: 'No Segment Change', noMarket: 'No Budget Market Change', noIncentive: 'No Incentive Plan Change', noRole: 'No Role Change', noProductionDate: 'No Production Date Change', noLanguage: 'No Language Change', noShift: 'No Shift Change', noSupervisor: 'No Supervisor Change' }; // Used to scan through the final payload and assign default values if missing optionalFields = ['budgetMarket', 'hierarchy', 'incentivePlan', 'primaryLanguage', 'secondaryLanguage', 'role', 'segment', 'shiftID', 'supervisor']; modifiedData: any; constructor( private utils: UtilsService ) { } ngOnInit() { } submitChanges() { this.modifiedData = this.payload; // Loop over all of the keys in our formData object for (const key in this.modifiedData.formData) { // Find shift by property if the key exists within our defined array if (this.modifiedData.formData.hasOwnProperty(key) && this.utils.isInArray(this.optionalFields, key)) { // If our object data doesnt have a value, set it to -1 if (!this.modifiedData.formData[key].length) { this.modifiedData.formData[key] = '-1'; } } } // Send to database console.log(this.modifiedData) } }
In this situation above, I am trying to set my signed this.payload data to a new variable called modifiedData . Then I change some data in this assignment.
However, as soon as I call the submitChanges() function, my HTML view receives updates with the changes made to modifiedData , although it did not subscribe to it.
I assume this has something to do with this.modifiedData = this.payload; somehow updating the source data ( payload ).
Is there a way to do this when payload not affected. I just clone this and make a few changes before posting it to my database query.