我有一堆由 ngFor 循环生成的离子芯片。我添加了使用变量选择所有离子芯片的功能tagDefaultColor。现在,当我想选择单个离子芯片时,它会选择所有离子芯片。
我想要实现的是能够使用切换所有按钮来选择每个按钮ion-chip或通过单击事件一一选择它们。一旦ion-chip被选择,它就会将其颜色更改为主要颜色。先感谢您。
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;
}
Run Code Online (Sandbox Code Playgroud)
selectAll() {
if (this.selectButtonText === 'SELECT ALL') {
this.selectButtonText = 'UNSELECT ALL'
this.tagDefaultColor = "primary";
} else {
this.selectButtonText = 'SELECT ALL'
this.tagDefaultColor = "secondary"
}
}
Run Code Online (Sandbox Code Playgroud)
changeTagColor(event) {
console.log(event.target);
if (this.tagDefaultColor === "secondary") {
this.tagDefaultColor = "primary"
} else {
this.tagDefaultColor = "secondary"
event.target.setAttribute('color', 'secondary')
}
}
Run Code Online (Sandbox Code Playgroud)
HTML部分
<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>
Run Code Online (Sandbox Code Playgroud)
您的所有芯片都绑定到相同的属性,因此如果您更改它们,它们都会更改。相反,您应该使用数组来单独分配它们,如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
编辑: 由于 ionic 不导出组件,遗憾的是您无法使用模板引用直接使用组件更改颜色。
正如您在评论中询问的那样,有一种简单的方法可以填充颜色数组,如下所示:
tagDefaultColor = Array(this.children.length).fill("secondary");
Run Code Online (Sandbox Code Playgroud)
这是 Stackblitz 示例。
| 归档时间: |
|
| 查看次数: |
3487 次 |
| 最近记录: |