Search code examples
angularangular-ngmodel2-way-object-databindingngmodel

2 way binding ngModel changes is also reflecting in its assigned temp variable(assigned on page load)


I have a 2 way binding model which i am assigning to a temp variable on page load. But the temp variable also taking the NgModel changes.

this.questionService.getAll(this.id, this.bcID).subscribe(_result => {
      this.questions = _result.data.filter(x => x.isDeleted === false);
      this.tempQuestions = _result.data.filter(x => x.isDeleted === false);
    });

Using KEndo UI Grid

<kendo-grid [data]="gridView"
              [height]="550"
              [skip]="gridState.skip"
              (edit)="editHandler($event)"">
this.gridView = process(this.questions, this.gridState);

Solution

  • Basically both the variables this.questions and this.tempQuestions are pointing to the same objects. To ensure changes doesn't reflect back to this.tempQuestions do a deep clone of the this.questions object.

    This will help

    this.questionService.getAll(this.id, this.bcID).subscribe(_result => {
      this.questions = _result.data.filter(x => x.isDeleted === false);
      this.tempQuestions = JSON.parse(JSON.stringify(this.questions));
    });