Muirik
Muirik

Reputation: 6289

Handling Array Building via Toggling Checkboxes in Angular 2 App

I am trying to come up with a simple toggle functionality where an array is built based on selections sent via checkboxes in my Angular 2 app. I seem to remember where you can handle toggling by setting one function to be equal to it's opposite, or something like that. These are the two functions I have for adding and removing array elements:

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;
    }
}

And then in my view I'm trying:

<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>

But this is not correct in it's current implementation. However, I do remember seeing something like this, though I can't remember the specific syntax. I've also considered using the "checked" JavaScript property in the conditional check. Would that be a better way to accomplish this? Or is there a simpler method to handle an array when items are added and removed based on checkbox selections?

UPDATE: After a suggestion from @ I am closer. With this implementation I can toggle of and off for one item, and the array will reflect that correctly. However, for more than one item selection it doesn't 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;
    }
}

Upvotes: 0

Views: 75

Answers (1)

Niladri
Niladri

Reputation: 5962

i have posted a more simplified version without adding any extra properties . please try the code below

private onItemSelected(item)
{
  const index: number = this.itemsArray.indexOf(item);
    if(index < 0){
         this.itemsArray.push(item);
         console.log(this.itemsArray);
         }
         else if(index != -1){
           this.itemsArray.splice(index,1);
           console.log(this.itemsArray);
         }      
   return this.itemsArray;
}

Upvotes: 1

Related Questions