简体   繁体   中英

ngFor with JSON object - Angular 2 ngmodel perspective

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.

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

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM