简体   繁体   English

带有JSON对象的ngFor-Angular 2 ngmodel透视图

[英]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: 示例代码如下: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: 并且example.ts中的代码如下:

 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 . 我面临的问题是,当我插入第二个输入时,即使第一个输入也更改为第二个,因为两者都引用同一个ngModel。例如,如果我添加“ GG”作为输入,则第一个记录将是GG。 When i enter "HH" then, first record GG changes to HH and result will be HH and HH. 当我输入“ HH”时,首先记录GG更改为HH,结果将为HH和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 从这里https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign了解有关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. _.clonelodash函数,它将传递一个新对象而不是引用。

You can also try a quick fix ( highly discouraged due to performance reasons ); 您也可以尝试快速修复(由于性能原因,不建议使用);

this.record.push(JSON.parse(JSON.stringify(username)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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