Trying to create a simple toggle function in my Angular 2 app where selections made via checkboxes build an array. I recall a method where toggling can be achieved by setting one function equal to its opposite. Here are the functions for adding and removing elements from the array:
private onItemSelected(item)
{
if (item)
{
this.itemsArray.push(item);
console.log(this.itemsArray);
return this.itemsArray;
}
}
private onItemRemoved(item)
{
if (item)
{
this.itemsArray.splice(item);
console.log(this.itemsArray);
return this.itemsArray;
}
}
In the view, attempting:
<md-checkbox (change)="onItemSelected('A') === onItemRemoved('A')">A</md-checkbox>
<md-checkbox (change)="onItemSelected('B') === onItemRemoved('B')">B</md-checkbox>
<md-checkbox (change)="onItemSelected('C') === onItemRemoved('C')">C</md-checkbox>
The current implementation is incorrect. Considering using the "checked" JavaScript property instead or exploring simpler methods to handle array changes based on checkbox selections.
UPDATE: Following a suggestion from @, getting closer. Can now toggle one item on and off correctly with the array reflecting that change. However, when selecting more than one item, it does not work:
private isChecked: boolean = false;
private onItemSelected(discipline)
{
this.isChecked = !this.isChecked;
if (item && this.isChecked)
{
this.itemsArray.push(item);
console.log(this.itemsArray);
}
else {
if (item && !this.isChecked)
{
this.itemsArray.splice(item);
console.log(this.itemsArray);
}
return this.itemsArray;
}
}