简体   繁体   中英

Push object into array in Angular

I have the problem with pushing object into array. I have array with objects inside. This component print it:

<div class="row"
  *ngFor="let element of dietList">
{{element.name}} {{ element.weight }}
</div>

Second add object to array but I would have possibility to add various type of object like: rice, chicken and so on. So I have created other array with object inside. This array don't contains wieght becouse user would have possibility to check his own value. So into second component I print name of product and input with local refference

<div *ngFor="let product of products">
  {{ product.name }}<input type="text" #weight>
  <button class="btn btn-primary" (click) = "onAddNewElement(product, weight.value)">Add</button>
</div>

onAddNewElement() method is very simple:

  onAddNewElement(element, weight){
    let newElement = element;
    newElement.weight = weight;
    this.dietService.newElement(newElement);
  }

newElement() method pushing object into array.

  newElement(element){
    PRODUCTS.push(element);
  }

It works but not like I want. When I add my first element everything is ok, but when I add next element values of first element is going to overwrite. Example: In first step I checked weight input on 120g (chicken for example). In second step I checked weight on 200g. In result 2 elements I going to weight value on 200g. First value every time is overwrite.

So here is what I think is happening.

You have an array of products, lets say:

var products = [{name: 'myOnlyProduct', weight: 120}]

Now you loop through that array of products in the *ngFor . You change the weight of that one object in your html and pass it to the onAddNewElement . In your onAddNewElement you update the old object with the new weight and pass it to newElement . newElement push the exact same object onto the array again.

What you need to do is create a new object before you change the weight and then push that to the array.

onAddNewElement(element, weight){
  let newElement = Object.assign({}, element); // make a copy
  newElement.weight = weight;
  this.dietService.newElement(newElement);
}

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