0

I'm using Angular 12.0.4.

My template has an Input like this:

<input type="text" [(ngModel)]="end.itemOne">
<button (click)="resetField()">reset</button>


<p>why does <strong style="color:red">this.start</strong> change with input value? </p>
<strong>{{ this.start.itemOne }}</strong>
<br>
<br>
<p>I need only <strong style="color:blue">this.end</strong> to change </p>
<strong>{{ this.end.itemOne }}</strong>

Inside the component:

start: any = {
    itemOne: 'item1',
    itemTwo: 'item2'
  };

  end!: any;

  ngOnInit(): void {
    this.end = this.start;
  }

  resetField(): void {
    this.end = this.start;
  }

Here is a stackblitz showing the issue: https://stackblitz.com/edit/angular-njppqj?file=src%2Fapp%2Fapp.component.ts

My problem is: If I change the input value and then click on the reset button I want this.end.itemOne value to become 'item1' again. Instead, when I change the input value, both this.start and this.end become equal in value.

Thanks in advance.

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
  • 2
    `ngOnInit(){this.resetField();}` `resetField():void{ this.end = {...this.start}}`. the whole point is to create copy of an object and put it into end. in your case start and end are referencing the same "pace in memory" – Andrei Jul 16 '21 at 18:22
  • Thanks for the response, but how do I avoid this behaviour? – Gustavo Branco Jul 16 '21 at 18:25
  • @gustavo-branco Object assignment by default is reference type you need to lose reference with some options that I mentioned in my answer – Alireza Ahmadi Jul 16 '21 at 18:35

1 Answers1

2

The way you are looking for is copy an object and lose its reference. So you have multiple option to achieve that.

Simplest way is spread notation:

this.end = {... this.start};

Another way is Object.assign

And for nested object you can even use:

<YourObjType> JSON.parse(JSON.stringify(originalObject));

https://stackblitz.com/edit/angular-sftvoi?file=src%2Fapp%2Fapp.component.ts

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
  • 1
    I never saw this before, thank you! I used this 'spread notation' way. – Gustavo Branco Jul 16 '21 at 18:38
  • 1
    the 'spread notation way' only works the first time the reset function runs, pressing the button a second time and the original problem comes back. Using JSON.parse solved the problem though. – Gustavo Branco Jul 16 '21 at 18:50