Reputation: 3247
I have bunch of ion-chips generated by ngFor loop. I have added select all ion-chips functionality using tagDefaultColor
variable. Right now when I want to select single ion-chip it selects all of them.
What I'm trying to achieve is being able to use toggle all button to select every ion-chip
or select them one by one with click event. Once ion-chip
is selected it changes its color to primary. Thank you in advance.
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.information = navParams.data.data;
this.children = [{ id: 1, name: 'Ginny Weasley' }, { id: 2, name: 'Harry Potter' }, { id: 3, name: 'Ronald Weasley' }, { id: 4, name: 'Luna Lovegood' }];
this.selectButtonText = 'SELECT ALL';
//this.tagSelectedColor = "primary";
this.tagDefaultColor = "secondary";
this.quantity = 0.0;
this.shareWithFamily = true;
}
selectAll() {
if (this.selectButtonText === 'SELECT ALL') {
this.selectButtonText = 'UNSELECT ALL'
this.tagDefaultColor = "primary";
} else {
this.selectButtonText = 'SELECT ALL'
this.tagDefaultColor = "secondary"
}
}
changeTagColor(event) {
console.log(event.target);
if (this.tagDefaultColor === "secondary") {
this.tagDefaultColor = "primary"
} else {
this.tagDefaultColor = "secondary"
event.target.setAttribute('color', 'secondary')
}
}
HTML part
<ion-item no-lines>
<ion-row>
<ion-col style="display: flex;align-items: center; justify-content: center">
<strong>Tag Students</strong>
<button ion-button full color="primary" class="select-all-btn" (click)="selectAll()">{{selectButtonText}}
</button>
</ion-col>
</ion-row>
</ion-item>
<div class="students-tags">
<ion-chip [id]="child.id" [color]="tagDefaultColor" (click)="changeTagColor($event)" *ngFor="let child of children">
<ion-label>{{child. name}}</ion-label>
</ion-chip>
</div>
Upvotes: 5
Views: 3806
Reputation: 10790
All your chips bind to same property so if you change that they will all change. Instead you should use array to assign them individually like below :
<ion-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>
changeTagColor(i:number) {
console.log(event.target);
if (this.tagDefaultColor[i] === "secondary") {
this.tagDefaultColor[i] = "primary"
} else {
this.tagDefaultColor[i] = "secondary"
// event.target.setAttribute('color', 'secondary') this is redundant
}
}
Edit: Since ionic doesn't export a component sadly you cant use template ref to change color directly with component.
And as you asked in comments there is an easy way to populate colors array like below :
tagDefaultColor = Array(this.children.length).fill("secondary");
Here is the Stackblitz sample.
Upvotes: 5