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

Krz*_*dyl 5 ionic3 angular

我有一堆由 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)

Eld*_*dar 5

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

<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 示例。

  • @carlhandy你可以用vue3得到类似的解决方案。无论您是否使用组合 API,语法都可能有所不同。基本上解释了您需要一个填充默认颜色名称的数组。将您的芯片颜色绑定到该数组的相应项目。单击后更改该位置的颜色。 (2认同)