Angular 8 creating a link between 2 separate variables

48 views Asked by At

I have an array which creates view based on the objects in it. The values inside the objects can be changed using ngModel. What happening is when I get the response of the array I set that same response in 2 different arrays (let's say mailConfig & tempMailConfig) of same type. Now when I change value in mailConfig, the state of tempMailConfig also changes.

Below is the way I assign the api response in both the variables (happens in OnInit) -

this._http.getTrainingConfigByKeys(this.mailConfigKeys).subscribe(response => {
  this.mailConfig = response;
  this.tempMailConfig = response;
});

Below is the HTML code -

<div class="form-group row" *ngFor="let config of mailConfig; let i=index">
  <label for="password" class="col-sm-12 col-md-4 col-form-label">{{config.title}} <span
    class="text-danger">*</span></label>
  <div class="col-sm-12" [ngClass]="{ 'col-md-6 col-lg-6': configValue.control.dirty, 'col-md-8 col-lg-8': !configValue.control.dirty }">
    <input type="text" [class.is-invalid]="false" #configValue="ngModel" [id]="config.propertyKey" [(ngModel)]="config.propertyValue" class="form-control" />
    <!-- Changes in config.propertyValue also changes the same object in tempMailConfig -->
  </div>
</div>

My project is written in Angular 8. I've written the same type of logic in other projects also only the Angular version was higher there and didn't faced any issues like this. I took a reference from this answer. This is fine when handling a single input field but for dynamic arrays how this can be solved? I don't want to use a reactive form as this doesn't have any complex operations.

1

There are 1 answers

0
Jignesh Panchal On

Try using below code to save same response in separate varibles.

this._http.getTrainingConfigByKeys(this.mailConfigKeys).subscribe(response => {
  this.mailConfig = response;
  this.tempMailConfig = [...response];
});

Or You may also use slice() method to create a new copy of the response data and assign in new varibale as below

this._http.getTrainingConfigByKeys(this.mailConfigKeys).subscribe(response => {
  this.mailConfig = response;
  this.tempMailConfig = response.slice();
});