Reputation: 1896
I have been trying to do a simple task of taking an input in textbox and listing the same. The sample code is below: Example.html:
<label>Name:</label>
<input type="text" [(ngModel)]="user.name" placeholder="Enter a name here">
<!-- conditionally display `yourName` -->
<button (click)="getData(user)">Add</button>
<hr>
<ul>
<li *ngFor="let rec of record">{{rec.name}}</li>
</ul>
And code in example.ts is below:
record:any[]=[];
user={"name":""};
getData(username:any){
this.record.push(username);
console.log(JSON.stringify(this.record));
}
Th problem i face is, when i insert the second input , even the first input changes as second as both refer to the same ngModel.For instance, if i add "GG" as input, first record will be GG . When i enter "HH" then, first record GG changes to HH and result will be HH and HH. Please help me understand where i went incorrect and help solve this.
Upvotes: 2
Views: 352
Reputation: 6311
Since your object has same key name every time while pushing the object will get updated with new value so how have do like this
this.record.push(Object.assign({}, username));
Read about Object.assign() from here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Upvotes: 2
Reputation: 4335
You have understood correctly that the problem is caused by the objects having same reference. As you are trying to store user details in a simple object you can easily clone the object by changing
this.record.push(username);
TO
this.record.push(_.clone(username));
The _.clone
is a lodash function which will pass a new object instead of a reference.
You can also try a quick fix ( highly discouraged due to performance reasons );
this.record.push(JSON.parse(JSON.stringify(username)));
Upvotes: 1