このパターンの考え方は、異なる配列を管理することです。ユーザーがオプションをクリックすると、オプションが選択/選択解除され、オプションの値が対応する配列にプッシュ/フィルタされます。array.filterを適用すると、関数に渡された配列参照が失われます
私は、呼び出された配列を管理する普遍的なメソッドを作成しようとしていますが、値をプッシュするとうまく動作しますが、フィルタリングでは機能しません。
角度成分のメソッド(動作しない)
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;
})
}
}
角度成分のメソッド(直接配列を基準にした場合に動作します)
potatoesArray = [];
manageOptions($event, testingArray) {
...
} else {
this.potatoesArray = testingArray.filter((option) => {
return option != optionValue;
})
}
}
注
console.log(testingArray === this.potatoesArray) // true
テンプレートの実装
<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>
から良いアイデアをそれを
this
を削除します推測する必要があります。 –@MikeMcCaughanはあなたに完全に同意しますが、エラーは表示されません:D – volna