Verthon
Verthon

Reputation: 3247

Ionic 3 add / remove tags

Hey working on select all or select one functionality.

Right now you can use select all / deselect all button, or add one tag to selected by simply clicking on it. I'm stuck on removing tag and child once someone deselect single tag. thank you for any suggestions.

What I'm trying to achive is to be able to:

  1. Select all tags using "select all" button, toggle their color, and add the all of the children names to array,
  2. Deselect all tags using "deselect all", toggle their color, and remove all of the children names from array,
  3. Select one or more tags by clicking on them, to change color and add to array,
  4. Deselect selected one or more tags by clicking on them, to change color to secondary and remove them from array.

function I'm using to select / deselect single item from an array

<div class="students-tags">
     <ion-chip #chip [id]="child.id" [color]="tagDefaultColor[i]" (click)="changeTagColor(i)"
        *ngFor="let child of children; let i = index">
     <ion-label>{{child. name}}</ion-label>
   </ion-chip>
</div>

changeTagColor(i) {
    if (this.tagDefaultColor[i] === "secondary") {
      this.tagDefaultColor[i] = "primary";
      this.selectedChildren.push(this.children[i]);
      console.log('After adding child: ', this.selectedChildren)
    } else {
      this.tagDefaultColor[i] = "secondary";
      this.selectedChildren.splice(i, 1);
      console.log('After removing child: ', this.selectedChildren)
    }
  }

Stackblitz link on pages/home/home.ts: https://stackblitz.com/edit/ionic-zzcptz

Upvotes: 0

Views: 139

Answers (1)

canbax
canbax

Reputation: 3856

The index you are passing to the function changeTagColor is wrong.

check the index like this.

changeTagColor(i) {
     if (this.tagDefaultColor[i] === "secondary") {
         this.tagDefaultColor[i] = "primary";
         this.selectedChildren.push(this.children[i]);
         console.log('After adding child: ', this.selectedChildren)
     } else {
         this.tagDefaultColor[i] = "secondary";
         this.selectedChildren.splice(i, 1);
         console.log('i: ', i)
         console.log('After removing child: ', this.selectedChildren)
     }
}

Also, always be very careful about if your objects are deep vs shallow copy.

Upvotes: 1

Related Questions