0

The idea of this pattern is to manage different arrays. When user clicks on an option it selects/deselects it and option's value is pushed into/filtered from the corresponding array.

I am trying to write the universal method that will manage the array it was called with, at the moment it works fine with pushing values but doesn't work with filtering.

Angular Component Methods (doesn't work)

 potatoesArray = [];

 manageOptions($event, testingArray) {

  const checkExistence = (array, value) => {
    return !(array.indexOf(value) >= 0)    
  }

  if ($event) {
    // SPAN value
    const optionValue = $event.target.innerText;      

    // Push if value isn't in array
    if (checkExistence(testingArray, optionValue)) {
      testingArray.push(optionValue);      

    // 'Remove' the value if it's in array  
    } else {
      testingArray = testingArray.filter((option) => {
        return option != optionValue;
      })
    }
}

Angular Component Methods (works if referenced to array directly)

 potatoesArray = [];

 manageOptions($event, testingArray) {

  ...

    } else {
      this.potatoesArray = testingArray.filter((option) => {
        return option != optionValue;
      })
    }
}

Note

console.log(testingArray === this.potatoesArray) // true

Template implementation

<div class="option" (click)='manageOptions($event, this.potatoesArray)'>
  <span>OPTION 1</span>
  ...                              
</div>

<div class="option" (click)='manageOptions($event, this.potatoesArray)'>
  <span>OPTION 2</span>                              
  ...
</div>

<div class="option" (click)='manageOptions($event, this.potatoesArray)'>
  <span>OPTION 3</span>                              
  ...
</div>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
volna
  • 2,452
  • 4
  • 25
  • 61

1 Answers1

2

Remove this from the template implementation

<div class="option" (click)='manageOptions($event, potatoesArray)'>
  <span>OPTION 1</span>
  ...                              
</div>

<div class="option" (click)='manageOptions($event, potatoesArray)'>
  <span>OPTION 2</span>                              
  ...
</div>

<div class="option" (click)='manageOptions($event, potatoesArray)'>
  <span>OPTION 3</span>                              
  ...
</div>
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • I did figure out that is not a problem of angular, but more a javascript behavior here is simplified question http://stackoverflow.com/questions/43953320/rewrite-array-from-the-function-using-argument-reference it shows up that it's kind of trick to set new value of an array if it is referenced from an argument. – volna May 13 '17 at 12:46