Ionic 3如何在点击事件中选择特定的离子芯片?

问题描述 投票:1回答:1

我有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;
  }
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部分

<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>
angular ionic3
1个回答
1
投票

您的所有筹码都绑定到相同的属性,因此,如果您进行更改,它们都会全部更改。相反,您应该使用数组单独分配它们,如下所示:

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

编辑:由于离子不会导出组件,因此您不能使用模板ref直接更改组件的颜色。

而且正如您在评论中问的那样,有一种简单的方法可以填充颜色数组,如下所示:

  tagDefaultColor = Array(this.children.length).fill("secondary");

Here是Stackblitz样本。

© www.soinside.com 2019 - 2024. All rights reserved.