0

I'm having a very weird problem in my Angular 2 application using the PrimeNG DataTable. It's possible to change data in my DataTable, using the [editable]"true" syntax.

The data in the DataTable is called = inschrijvingen. I'm doing this.originalInschrijvingen = this.inschrijvingen to create a 'copy' before the user can change the data so I can compare the changes in a later stage. But for some reason is the DataTable data binding to both originalInschrijvingen and inschrijvingen.

Here is my code:

onRowSelectUser(event) { //This is a different DataTable than the editable DataTable
    this.getGebruikerZijnInschrijvingen(res => {
      this.createRoleID(res => {
        let selectedIds = this.gebruikerZijnInschrijvingen.map(it => it.DefUnitID);
        this.selectedInschrijvingen = this.inschrijvingen.filter(inv => selectedIds.indexOf(inv.ID) != -1);
        this.originalInschrijvingen = this.selectedInschrijvingen;
      })
    })
  }
Milan_w
  • 291
  • 2
  • 4
  • 17
  • 2
    maybe reading about references in programming would help. https://en.wikipedia.org/wiki/Reference_(computer_science) – toskv Jun 08 '17 at 15:00
  • Thanks for this! I didn't knew it was referencing instead of 'copying'. Thanks! – Milan_w Jun 08 '17 at 15:26
  • @Pengyy Thanks for the reply but I think I found an answer already = [Link](https://stackoverflow.com/a/21896214/4461137) – Milan_w Jun 08 '17 at 15:39
  • @Milan_w ok, for me, I would recommend you avoid using the way mentioned by that link for `json.parse` and `json.stringify` may lead to problems. – Pengyy Jun 08 '17 at 15:42
  • @Pengyy Okay, I'll look into your solution! Thanks! – Milan_w Jun 08 '17 at 15:47

1 Answers1

0

this.selectedInschrijvingen seems to be an array and in Javascript when you assign one array to another using = operator they are copied by reference, hence they represent same array.

You can do below,

this.originalInschrijvingen = this.selectedInschrijvingen.slice();

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Hope this helps!!

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69
  • Thank you for the explanation!! At least I understand now why this was happening, it was driving me crazy! But your solution doesn't quite work, it still updates both arrays? Any more ideas? – Milan_w Jun 08 '17 at 15:22
  • I have found a way to do this. [This guy](https://stackoverflow.com/a/21896214/4461137) had an idea without any upvotes, but it seems to be working for me. – Milan_w Jun 08 '17 at 15:35