1

i have 2 liste in my class and i have a functon that take one element from an first array and push it to second array .my problem is if i change the element of second array the same element from first array get changed i triied with a onchange function and with [(ngModel)]

<div >
                <p>{{item.name}}</p>
                <p [hidden]="true" id={{item.name}} >
                    <input   type="text" (change)=t($event,item.id) >
                </p>
              </div>


t(event,id:number)
{
  console.log(event.target.value);
  this.nodes2.find(a=>a.id===id).name=event.target.value;


}

//use this for pushing item
  droppp(ev) {
    ev.preventDefault();
    //console.log(this.dragedElement)
    var nodtmp:ExampleFlatNode[];
    nodtmp=this.nodes2;
    nodtmp.push(this.dragedElement);
    this.nodes2=nodtmp;

  }

1 Answers1

0

The problem of changing values of properties of dragged object has nothing to ngModel, neither onChange event. Problem is because you do not copy the object itself but just its reference. In drop function do not push object this.dragedElement but change it to looks like nodtmp.push({...this.dragedElement}) which should create a copy of dropped object. If you need deeper copy of object, use lodash library with deepClone function.

Filip Kováč
  • 499
  • 8
  • 15
  • thank you for respondng,after changing to nodtmp = {...this.nodes2} the same thing happens – Hanini Mohamed Mar 01 '21 at 23:44
  • @HaniniMohamed I changed my answer, i misstaken the array with the object which should be instationed. By this, be aware that {....oldObject} just do one level copy, so if has another object inside, its again reference to original object. Good examples are [here](https://stackoverflow.com/questions/28150967/typescript-cloning-object). – Filip Kováč Mar 02 '21 at 07:04